react-semaphor 0.1.302 → 0.1.303

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 (44) hide show
  1. package/dist/appearance/index.cjs +1 -1
  2. package/dist/appearance/index.js +1 -1
  3. package/dist/brand-studio/index.cjs +5 -5
  4. package/dist/brand-studio/index.js +334 -385
  5. package/dist/chunks/{dashboard-controls-CZuC_QjN.js → dashboard-controls-BCJZOzrL.js} +10 -11
  6. package/dist/chunks/{dashboard-controls-BkuB9TQX.js → dashboard-controls-CVFoOPti.js} +9 -9
  7. package/dist/chunks/{dashboard-filter-controls-button-2I1ltWQ9.js → dashboard-filter-controls-button-C-e7230k.js} +1 -1
  8. package/dist/chunks/{dashboard-filter-controls-button-kfb_T18o.js → dashboard-filter-controls-button-Cfbac4Jw.js} +4 -4
  9. package/dist/chunks/{dashboard-json-C3v6rBdp.js → dashboard-json-BM5ywMgp.js} +1 -1
  10. package/dist/chunks/{dashboard-json-Df6v2Jem.js → dashboard-json-BzvLPhGM.js} +3 -3
  11. package/dist/chunks/{dashboard-summary-settings-dialog-BBALEHJQ.js → dashboard-summary-settings-dialog-BdxKl1UF.js} +1 -1
  12. package/dist/chunks/{dashboard-summary-settings-dialog-DKAaWq-G.js → dashboard-summary-settings-dialog-ChK3344r.js} +2 -2
  13. package/dist/chunks/{edit-dashboard-visual-D8L0cl_U.js → edit-dashboard-visual-D725CWD5.js} +9 -10
  14. package/dist/chunks/{edit-dashboard-visual-CGBYahAK.js → edit-dashboard-visual-nNaZ2IK1.js} +33 -33
  15. package/dist/chunks/{index-eM6MU4q_.js → index-BWjB_9uz.js} +222 -227
  16. package/dist/chunks/{index-uRJmUpof.js → index-CJdxSyQq.js} +679 -656
  17. package/dist/chunks/{index-BmoR3VQT.js → index-CYWgnME0.js} +19429 -19168
  18. package/dist/chunks/index-DRlMUglg.js +4 -0
  19. package/dist/chunks/{palette-326-dgn0.js → palette-B9DJXMGo.js} +7 -2
  20. package/dist/chunks/{palette-jd7xiGTg.js → palette-DGOzbtsn.js} +23 -3
  21. package/dist/chunks/{resource-management-panel-C_c-BwrC.js → resource-management-panel-CE0-NcLL.js} +3 -3
  22. package/dist/chunks/{resource-management-panel-DrcEEARD.js → resource-management-panel-mJmc5dMT.js} +1 -1
  23. package/dist/chunks/{rotate-ccw-BugHcM1w.js → rotate-ccw-Bs7YJn10.js} +1 -1
  24. package/dist/chunks/{rotate-ccw-yFwqBFJZ.js → rotate-ccw-YsjQwpKm.js} +1 -1
  25. package/dist/chunks/{save-CaybXtdd.js → save-Bj1y1rug.js} +1 -1
  26. package/dist/chunks/{save-DU0FXUlM.js → save-CUrexoNl.js} +1 -1
  27. package/dist/chunks/{switch-AmoR1YIA.js → switch-CiEX68py.js} +24 -24
  28. package/dist/chunks/{switch-CZtMtqEj.js → switch-oojO-gal.js} +1378 -1373
  29. package/dist/chunks/{use-create-flow-overlay-state-84Xe8VrP.js → use-create-flow-overlay-state-BHDKxe7I.js} +4 -4
  30. package/dist/chunks/{use-create-flow-overlay-state-CiKVJGWF.js → use-create-flow-overlay-state-D2I2wNey.js} +1 -1
  31. package/dist/chunks/{use-visual-utils-z3ifg6Fd.js → use-visual-utils-CjFzlR0P.js} +2 -2
  32. package/dist/chunks/{use-visual-utils-lp5DfmvL.js → use-visual-utils-DYDXMl5v.js} +1 -1
  33. package/dist/dashboard/index.cjs +1 -1
  34. package/dist/dashboard/index.js +1 -1
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.js +8 -8
  37. package/dist/style.css +1 -1
  38. package/dist/surfboard/index.cjs +1 -1
  39. package/dist/surfboard/index.js +2 -2
  40. package/dist/types/main.d.ts +1 -0
  41. package/package.json +1 -1
  42. package/dist/chunks/braces-CpOcaBNm.js +0 -6
  43. package/dist/chunks/braces-TYclg8Hl.js +0 -23
  44. package/dist/chunks/index-Cxb9UUro.js +0 -4
@@ -1,24 +1,24 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),C=require("react"),n=require("./index-eM6MU4q_.js"),t=require("./switch-AmoR1YIA.js"),ct=require("./use-visual-utils-lp5DfmvL.js"),Me=require("./use-create-flow-overlay-state-CiKVJGWF.js"),ba=require("react-dom");require("./index-Cxb9UUro.js");const ms=require("./rotate-ccw-BugHcM1w.js"),ja=require("./palette-326-dgn0.js"),va=require("./braces-CpOcaBNm.js");function ya(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const l=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,l.get?l:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const zt=ya(C);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),C=require("react"),n=require("./index-BWjB_9uz.js"),t=require("./switch-CiEX68py.js"),ct=require("./use-visual-utils-DYDXMl5v.js"),Me=require("./use-create-flow-overlay-state-D2I2wNey.js"),ja=require("react-dom");require("./index-DRlMUglg.js");const ms=require("./rotate-ccw-Bs7YJn10.js"),An=require("./palette-B9DJXMGo.js");function va(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const l=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,l.get?l:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const zt=va(C);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const Na=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"}]]);/**
6
+ */const ya=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
7
  * @license lucide-react v0.453.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const Ca=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"}]]);/**
11
+ */const Na=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
12
  * @license lucide-react v0.453.0 - ISC
13
13
  *
14
14
  * This source code is licensed under the ISC license.
15
15
  * See the LICENSE file in the root directory of this source tree.
16
- */const An=t.createLucideIcon("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/**
16
+ */const Mn=t.createLucideIcon("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/**
17
17
  * @license lucide-react v0.453.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Mn=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"}]]);/**
21
+ */const Ln=t.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
22
22
  * @license lucide-react v0.453.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
@@ -28,42 +28,42 @@
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Sa=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"}]]);/**
31
+ */const Ca=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
32
  * @license lucide-react v0.453.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const Ln=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"}]]);/**
36
+ */const Fn=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
37
  * @license lucide-react v0.453.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const wa=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"}]]);/**
41
+ */const Sa=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
42
  * @license lucide-react v0.453.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Ta=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"}]]);/**
46
+ */const wa=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
47
  * @license lucide-react v0.453.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const Fn=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"}]]);/**
51
+ */const Rn=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
52
  * @license lucide-react v0.453.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const Ea=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"}]]);/**
56
+ */const Ta=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
57
  * @license lucide-react v0.453.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const Ia=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"}]]);/**
61
+ */const Ea=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
62
  * @license lucide-react v0.453.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const ka=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"}]]);/**
66
+ */const Ia=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
67
  * @license lucide-react v0.453.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
@@ -73,12 +73,12 @@
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const Da=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"}]]);/**
76
+ */const ka=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
77
  * @license lucide-react v0.453.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const Aa=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"}]]);/**
81
+ */const Da=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
82
  * @license lucide-react v0.453.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
@@ -93,12 +93,12 @@
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const Ma=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"}]]);/**
96
+ */const Aa=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"}]]);/**
97
97
  * @license lucide-react v0.453.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const La=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
101
+ */const Ma=t.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
102
102
  * @license lucide-react v0.453.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
@@ -108,67 +108,67 @@
108
108
  *
109
109
  * This source code is licensed under the ISC license.
110
110
  * See the LICENSE file in the root directory of this source tree.
111
- */const Fa=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"}]]);/**
111
+ */const La=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"}]]);/**
112
112
  * @license lucide-react v0.453.0 - ISC
113
113
  *
114
114
  * This source code is licensed under the ISC license.
115
115
  * See the LICENSE file in the root directory of this source tree.
116
- */const Ra=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"}]]);/**
116
+ */const Fa=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"}]]);/**
117
117
  * @license lucide-react v0.453.0 - ISC
118
118
  *
119
119
  * This source code is licensed under the ISC license.
120
120
  * See the LICENSE file in the root directory of this source tree.
121
- */const Oa=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"}]]);/**
121
+ */const Ra=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"}]]);/**
122
122
  * @license lucide-react v0.453.0 - ISC
123
123
  *
124
124
  * This source code is licensed under the ISC license.
125
125
  * See the LICENSE file in the root directory of this source tree.
126
- */const Pa=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"}]]);/**
126
+ */const Oa=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"}]]);/**
127
127
  * @license lucide-react v0.453.0 - ISC
128
128
  *
129
129
  * This source code is licensed under the ISC license.
130
130
  * See the LICENSE file in the root directory of this source tree.
131
- */const Ba=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"}]]);/**
131
+ */const Pa=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"}]]);/**
132
132
  * @license lucide-react v0.453.0 - ISC
133
133
  *
134
134
  * This source code is licensed under the ISC license.
135
135
  * See the LICENSE file in the root directory of this source tree.
136
- */const Va=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"}]]);/**
136
+ */const Ba=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"}]]);/**
137
137
  * @license lucide-react v0.453.0 - ISC
138
138
  *
139
139
  * This source code is licensed under the ISC license.
140
140
  * See the LICENSE file in the root directory of this source tree.
141
- */const za=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
141
+ */const Va=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
142
142
  * @license lucide-react v0.453.0 - ISC
143
143
  *
144
144
  * This source code is licensed under the ISC license.
145
145
  * See the LICENSE file in the root directory of this source tree.
146
- */const _a=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"}]]);/**
146
+ */const za=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"}]]);/**
147
147
  * @license lucide-react v0.453.0 - ISC
148
148
  *
149
149
  * This source code is licensed under the ISC license.
150
150
  * See the LICENSE file in the root directory of this source tree.
151
- */const qa=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 Rn({storeValue:s,defaultValue:a="",onStoreUpdate:r,delay:l=300}){const[u,c]=C.useState(s??a),o=C.useRef(null),d=C.useRef(u),i=C.useRef(s),x=C.useRef(!1),h=C.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null),x.current&&d.current!==(i.current??a)&&(r(d.current),i.current=d.current)},[a,r]);C.useEffect(()=>{if(s!==i.current){o.current&&(clearTimeout(o.current),o.current=null);const f=s??a;c(f),d.current=f,i.current=s,x.current=!1}},[s,a]),C.useEffect(()=>{if(x.current)return o.current=setTimeout(()=>{h()},l),()=>{o.current&&(clearTimeout(o.current),o.current=null)}},[l,h,u]),C.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const v=C.useCallback(f=>{const m=f??a;x.current=!0,d.current=m,c(m)},[a]);return{value:u,onChange:v,flush:h}}function $a({open:s,onOpenChange:a}){const[r,l]=C.useState([]),{updateDataSource:u}=t.useEditorActions(),{selectedEntities:c}=n.useAssistantContextEntities("dashboard");C.useEffect(()=>{s&&l([])},[s]);const o=m=>{l(g=>g.some(b=>n.areContextEntitiesEqual(b,m))?g.filter(b=>!n.areContextEntitiesEqual(b,m)):[...g,m])},d=()=>{l([...c])},i=()=>{l([])},x=()=>{if(r.length===0)return;const m=r[0],g=m.connectionId||"",y=m.connectionType||"",w=r.some(B=>B.type==="dataset")?"semanticDomain":"database";u({connectionId:g,connectionType:y,mode:w,selectedEntities:r}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,v=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},f=m=>r.some(g=>n.areContextEntitiesEqual(g,m));return c.length===0?e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-md",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"No Data Available"}),e.jsx(n.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(n.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(n.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:r.length===c.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:i,disabled:r.length===0,children:"Clear All"})]}),e.jsxs(n.Badge,{variant:"secondary",children:[r.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((m,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",f(m)&&"border-primary bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:f(m),onCheckedChange:()=>o(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:n.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:v(m)})]}),e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),e.jsx(n.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:x,disabled:r.length===0,children:["Select"," ",r.length>0?`(${r.length})`:""]})]})})})]})})}function Ka({initialJoinPlan:s,availableDataSources:a}){const[r,l]=C.useState(s),[u,c]=C.useState(new Set),o=()=>{const I=r.joins.length>0?Math.max(...r.joins.map(N=>N.sequence))+1:1,T={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:[]}]};l({...r,joins:[...r.joins,T]}),c(new Set([...u,T.id]))},d=I=>{l({...r,joins:r.joins.filter(T=>T.id!==I)}),c(new Set([...u].filter(T=>T!==I)))},i=(I,T)=>{var D,L,R,p,F;const N=r.joins.find(k=>k.id===I);if(!N)return;const M={...N,...T};if((D=M.source)!=null&&D.name&&((L=M.target)!=null&&L.name)&&M.source.name===M.target.name){n.ue.error("Self-joins are not yet supported",{description:`Joining ${M.source.name} to itself is not currently supported. Please select a different target table.`});return}const j=r.joins.filter(k=>{var P;return k.id!==I&&k.target.name===((P=M.target)==null?void 0:P.name)});if((R=M.target)!=null&&R.name&&j.length>0){n.ue.error("Duplicate join targets are not supported",{description:`The table ${M.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const O=r.joins.map(k=>k.id===I?M:k);if((p=M.source)!=null&&p.name&&((F=M.target)!=null&&F.name)&&M.joinKeyGroups[0].keys.length===0){const k=a.find(_=>{var q;return _.name===((q=M.source)==null?void 0:q.name)}),P=a.find(_=>{var q;return _.name===((q=M.target)==null?void 0:q.name)}),V={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(P==null?void 0:P.name)||"",entityName:(P==null?void 0:P.name)||"",entityType:(P==null?void 0:P.type)||"table"},operator:"="},z=[...M.joinKeyGroups];z[0]={...z[0],keys:[V]},M.joinKeyGroups=z,O[O.findIndex(_=>_.id===I)]=M}l({...r,joins:O})};return{joinPlan:r,expandedJoins:u,setJoinPlan:l,addJoin:o,removeJoin:d,updateJoin:i,moveJoinUp:I=>{const T=r.joins.findIndex(N=>N.id===I);if(T>0){const N=[...r.joins],M={...N[T]},j={...N[T-1]};N[T]=j,N[T-1]=M,N.forEach((D,L)=>{D.sequence=L+1});const O={...r,joins:N};l(O)}},moveJoinDown:I=>{const T=r.joins.findIndex(N=>N.id===I);if(T<r.joins.length-1){const N=[...r.joins],M={...N[T]},j={...N[T+1]};N[T]=j,N[T+1]=M,N.forEach((D,L)=>{D.sequence=L+1});const O={...r,joins:N};l(O)}},toggleJoinExpansion:I=>{const T=new Set(u);T.has(I)?T.delete(I):T.add(I),c(T)},getAvailableSourceEntities:I=>{if(r.joins.length===0)return a;const T=r.joins.findIndex(M=>M.id===I);if(T===0)return a.filter(M=>M.name===r.baseEntity.name);const N=new Set;return r.baseEntity.name&&N.add(r.baseEntity.name),r.joins.slice(0,T).forEach(M=>{N.add(M.source.name),N.add(M.target.name)}),a.filter(M=>N.has(M.name))},getAvailableTargetEntities:I=>a.filter(T=>T.name!==I),addJoinKeyGroup:I=>{const T=r.joins.find(M=>M.id===I);if(!T)return;const N=[...T.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(I,{joinKeyGroups:N})},updateGroupOperator:(I,T,N)=>{const M=r.joins.find(O=>O.id===I);if(!M)return;const j=[...M.joinKeyGroups];j[T]={...j[T],operator:N},i(I,{joinKeyGroups:j})},removeJoinKeyGroup:(I,T)=>{const N=r.joins.find(j=>j.id===I);if(!N)return;const M=[...N.joinKeyGroups];M.splice(T,1),i(I,{joinKeyGroups:M})},addJoinKey:(I,T)=>{const N=r.joins.find(L=>L.id===I);if(!N)return;const M=a.find(L=>L.name===N.source.name),j=a.find(L=>L.name===N.target.name),O=[...N.joinKeyGroups],D={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(j==null?void 0:j.name)||"",entityName:(j==null?void 0:j.name)||"",entityType:(j==null?void 0:j.type)||"table"},operator:"="};O[T]={...O[T],keys:[...O[T].keys,D]},i(I,{joinKeyGroups:O})},updateJoinKey:(I,T,N,M,j)=>{const O=r.joins.find(F=>F.id===I);if(!O)return;const D=a.find(F=>F.name===O.source.name),L=a.find(F=>F.name===O.target.name),R=[...O.joinKeyGroups],p=R[T].keys[N];M==="sourceColumnName"&&D?R[T].keys[N]={...p,source:{...p.source,name:j}}:M==="targetColumnName"&&L?R[T].keys[N]={...p,target:{...p.target,name:j}}:M==="operator"&&(R[T].keys[N]={...p,operator:j}),i(I,{joinKeyGroups:R})},removeJoinKey:(I,T,N)=>{const M=r.joins.find(O=>O.id===I);if(!M)return;const j=[...M.joinKeyGroups];j[T].keys.splice(N,1),i(I,{joinKeyGroups:j})},generateSQLPreview:()=>{const I=[...r.joins].sort((M,j)=>M.sequence-j.sequence),T=r.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
151
+ */const _a=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 On({storeValue:s,defaultValue:a="",onStoreUpdate:r,delay:l=300}){const[u,c]=C.useState(s??a),o=C.useRef(null),d=C.useRef(u),i=C.useRef(s),x=C.useRef(!1),h=C.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null),x.current&&d.current!==(i.current??a)&&(r(d.current),i.current=d.current)},[a,r]);C.useEffect(()=>{if(s!==i.current){o.current&&(clearTimeout(o.current),o.current=null);const f=s??a;c(f),d.current=f,i.current=s,x.current=!1}},[s,a]),C.useEffect(()=>{if(x.current)return o.current=setTimeout(()=>{h()},l),()=>{o.current&&(clearTimeout(o.current),o.current=null)}},[l,h,u]),C.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const v=C.useCallback(f=>{const m=f??a;x.current=!0,d.current=m,c(m)},[a]);return{value:u,onChange:v,flush:h}}function qa({open:s,onOpenChange:a}){const[r,l]=C.useState([]),{updateDataSource:u}=t.useEditorActions(),{selectedEntities:c}=n.useAssistantContextEntities("dashboard");C.useEffect(()=>{s&&l([])},[s]);const o=m=>{l(g=>g.some(b=>n.areContextEntitiesEqual(b,m))?g.filter(b=>!n.areContextEntitiesEqual(b,m)):[...g,m])},d=()=>{l([...c])},i=()=>{l([])},x=()=>{if(r.length===0)return;const m=r[0],g=m.connectionId||"",y=m.connectionType||"",w=r.some(B=>B.type==="dataset")?"semanticDomain":"database";u({connectionId:g,connectionType:y,mode:w,selectedEntities:r}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,v=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},f=m=>r.some(g=>n.areContextEntitiesEqual(g,m));return c.length===0?e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-md",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"No Data Available"}),e.jsx(n.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(n.DialogFooter,{children:e.jsx(t.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(n.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"sm",onClick:d,disabled:r.length===c.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:i,disabled:r.length===0,children:"Clear All"})]}),e.jsxs(n.Badge,{variant:"secondary",children:[r.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((m,g)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",f(m)&&"border-primary bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:f(m),onCheckedChange:()=>o(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:n.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:v(m)})]}),e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),e.jsx(n.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(t.Button,{onClick:x,disabled:r.length===0,children:["Select"," ",r.length>0?`(${r.length})`:""]})]})})})]})})}function $a({initialJoinPlan:s,availableDataSources:a}){const[r,l]=C.useState(s),[u,c]=C.useState(new Set),o=()=>{const I=r.joins.length>0?Math.max(...r.joins.map(N=>N.sequence))+1:1,T={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:[]}]};l({...r,joins:[...r.joins,T]}),c(new Set([...u,T.id]))},d=I=>{l({...r,joins:r.joins.filter(T=>T.id!==I)}),c(new Set([...u].filter(T=>T!==I)))},i=(I,T)=>{var D,L,R,p,F;const N=r.joins.find(k=>k.id===I);if(!N)return;const M={...N,...T};if((D=M.source)!=null&&D.name&&((L=M.target)!=null&&L.name)&&M.source.name===M.target.name){n.ue.error("Self-joins are not yet supported",{description:`Joining ${M.source.name} to itself is not currently supported. Please select a different target table.`});return}const j=r.joins.filter(k=>{var P;return k.id!==I&&k.target.name===((P=M.target)==null?void 0:P.name)});if((R=M.target)!=null&&R.name&&j.length>0){n.ue.error("Duplicate join targets are not supported",{description:`The table ${M.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const O=r.joins.map(k=>k.id===I?M:k);if((p=M.source)!=null&&p.name&&((F=M.target)!=null&&F.name)&&M.joinKeyGroups[0].keys.length===0){const k=a.find(_=>{var q;return _.name===((q=M.source)==null?void 0:q.name)}),P=a.find(_=>{var q;return _.name===((q=M.target)==null?void 0:q.name)}),V={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(P==null?void 0:P.name)||"",entityName:(P==null?void 0:P.name)||"",entityType:(P==null?void 0:P.type)||"table"},operator:"="},z=[...M.joinKeyGroups];z[0]={...z[0],keys:[V]},M.joinKeyGroups=z,O[O.findIndex(_=>_.id===I)]=M}l({...r,joins:O})};return{joinPlan:r,expandedJoins:u,setJoinPlan:l,addJoin:o,removeJoin:d,updateJoin:i,moveJoinUp:I=>{const T=r.joins.findIndex(N=>N.id===I);if(T>0){const N=[...r.joins],M={...N[T]},j={...N[T-1]};N[T]=j,N[T-1]=M,N.forEach((D,L)=>{D.sequence=L+1});const O={...r,joins:N};l(O)}},moveJoinDown:I=>{const T=r.joins.findIndex(N=>N.id===I);if(T<r.joins.length-1){const N=[...r.joins],M={...N[T]},j={...N[T+1]};N[T]=j,N[T+1]=M,N.forEach((D,L)=>{D.sequence=L+1});const O={...r,joins:N};l(O)}},toggleJoinExpansion:I=>{const T=new Set(u);T.has(I)?T.delete(I):T.add(I),c(T)},getAvailableSourceEntities:I=>{if(r.joins.length===0)return a;const T=r.joins.findIndex(M=>M.id===I);if(T===0)return a.filter(M=>M.name===r.baseEntity.name);const N=new Set;return r.baseEntity.name&&N.add(r.baseEntity.name),r.joins.slice(0,T).forEach(M=>{N.add(M.source.name),N.add(M.target.name)}),a.filter(M=>N.has(M.name))},getAvailableTargetEntities:I=>a.filter(T=>T.name!==I),addJoinKeyGroup:I=>{const T=r.joins.find(M=>M.id===I);if(!T)return;const N=[...T.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(I,{joinKeyGroups:N})},updateGroupOperator:(I,T,N)=>{const M=r.joins.find(O=>O.id===I);if(!M)return;const j=[...M.joinKeyGroups];j[T]={...j[T],operator:N},i(I,{joinKeyGroups:j})},removeJoinKeyGroup:(I,T)=>{const N=r.joins.find(j=>j.id===I);if(!N)return;const M=[...N.joinKeyGroups];M.splice(T,1),i(I,{joinKeyGroups:M})},addJoinKey:(I,T)=>{const N=r.joins.find(L=>L.id===I);if(!N)return;const M=a.find(L=>L.name===N.source.name),j=a.find(L=>L.name===N.target.name),O=[...N.joinKeyGroups],D={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(j==null?void 0:j.name)||"",entityName:(j==null?void 0:j.name)||"",entityType:(j==null?void 0:j.type)||"table"},operator:"="};O[T]={...O[T],keys:[...O[T].keys,D]},i(I,{joinKeyGroups:O})},updateJoinKey:(I,T,N,M,j)=>{const O=r.joins.find(F=>F.id===I);if(!O)return;const D=a.find(F=>F.name===O.source.name),L=a.find(F=>F.name===O.target.name),R=[...O.joinKeyGroups],p=R[T].keys[N];M==="sourceColumnName"&&D?R[T].keys[N]={...p,source:{...p.source,name:j}}:M==="targetColumnName"&&L?R[T].keys[N]={...p,target:{...p.target,name:j}}:M==="operator"&&(R[T].keys[N]={...p,operator:j}),i(I,{joinKeyGroups:R})},removeJoinKey:(I,T,N)=>{const M=r.joins.find(O=>O.id===I);if(!M)return;const j=[...M.joinKeyGroups];j[T].keys.splice(N,1),i(I,{joinKeyGroups:j})},generateSQLPreview:()=>{const I=[...r.joins].sort((M,j)=>M.sequence-j.sequence),T=r.baseEntity;if(!T.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
152
152
  FROM ${T.name}`;return I.forEach(M=>{const j=a.find(L=>L.name===M.target.name);if(!j)return;const O=M.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const R=L.keys.filter(p=>{var F,k,P,V;return((F=p.source)==null?void 0:F.name)&&((k=p.target)==null?void 0:k.name)&&((P=p.source)==null?void 0:P.entityName)&&((V=p.target)==null?void 0:V.entityName)}).map(p=>`${p.source.entityName}.${p.source.name} ${p.operator} ${p.target.entityName}.${p.target.name}`);return R.length>1?`(${R.join(` ${L.operator} `)})`:R[0]}).filter(Boolean),D=O.length>1?O.join(" OR "):O[0]||"condition_here";N+=`
153
153
  ${M.joinType} JOIN ${j.name}
154
- ON ${D}`}),N},isValidConfiguration:()=>!(!r.baseEntity.name||r.joins.some(M=>!M.source.name||!M.target.name)||r.joins.some(M=>M.joinKeyGroups.some(j=>j.keys.length===0))||r.joins.some(M=>M.joinKeyGroups.some(j=>j.keys.some(O=>!O.source.name||!O.target.name||!O.operator))))}}function Ga({joinPlan:s,availableDataSources:a,onSave:r,onRemove:l,onCancel:u}){const{setCardConfig:c}=t.useEditorActions();t.useEditorStore(D=>D.card.config);const{columnGroups:o}=n.useColumns(),d=o.filter(D=>D.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:i,expandedJoins:x,setJoinPlan:h,addJoin:v,removeJoin:f,updateJoin:m,moveJoinUp:g,moveJoinDown:y,toggleJoinExpansion:b,getAvailableSourceEntities:w,getAvailableTargetEntities:A,addJoinKeyGroup:B,updateGroupOperator:S,removeJoinKeyGroup:E,addJoinKey:I,updateJoinKey:T,removeJoinKey:N,generateSQLPreview:M,isValidConfiguration:j}=Ka({initialJoinPlan:s,availableDataSources:a}),O=D=>{const L=d.find(R=>R.entityName===D);return(L==null?void 0:L.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:i.baseEntity.name,onValueChange:D=>{const L=a.find(R=>R.name===D);h({...i,baseEntity:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:D,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(D=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:M()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:v,children:[e.jsx(n.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.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:i.joins.map(D=>{const L=a.find(F=>F.name===D.source.name),R=a.find(F=>F.name===D.target.name),p=x.has(D.id);return e.jsxs(n.Card,{className:"border",children:[e.jsx(n.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{children:D.sequence}),e.jsxs(n.CardTitle,{className:"text-sm",children:["Join ",D.sequence,L&&R&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",L.name," → ",R.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===1,children:e.jsx(n.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(D.id),disabled:D.sequence===i.joins.length,children:e.jsx(n.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(D.id),children:p?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:()=>f(D.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),p&&e.jsxs(n.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:D.source.name,onValueChange:F=>{const k=a.find(P=>P.name===F);m(D.id,{source:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:F,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:w(D.id).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(n.Badge,{variant:"outline",className:"text-xs",children:F.type}),F.name]})},F.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:D.joinType,onValueChange:F=>m(D.id,{joinType:F}),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:D.target.name,onValueChange:F=>{const k=a.find(P=>P.name===F);m(D.id,{target:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:F,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},disabled:!D.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:D.source.name?A(D.source.name).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(n.Badge,{variant:"outline",className:"text-xs",children:F.type}),F.name,F.name===D.source.name&&e.jsx(n.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},F.name)):[]})]})]})]}),D.source.name&&D.target.name&&L&&R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>B(D.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((F,k)=>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 ",k+1]}),k>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:F.operator,onValueChange:P=>S(D.id,k,P),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(D.id,k),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[F.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:F.keys.map((P,V)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[V>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:F.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.source.name,onValueChange:z=>T(D.id,k,V,"sourceColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:O(D.source.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:P.operator,onValueChange:z=>T(D.id,k,V,"operator",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.target.name,onValueChange:z=>T(D.id,k,V,"targetColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:O(D.target.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,k,V),children:e.jsx(t.X,{className:"size-3.5"})})]},P.id||V))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>I(D.id,k),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},F.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{l(),u()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:u,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>r(i),disabled:!j(),children:"Save"})]})]})}function On({children:s,open:a,onOpenChange:r,joinPlan:l,availableDataSources:u,onRemove:c,onSave:o,onCancel:d}){return e.jsxs(n.Dialog,{open:a,onOpenChange:r,children:[e.jsxs(n.DialogContent,{className:"max-w-4xl",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Join Configuration"}),e.jsx(n.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ga,{joinPlan:l,availableDataSources:u,onSave:o,onCancel:d,onRemove:c})]}),s]})}function Ua({joins:s,baseEntityId:a,availableDataSources:r,generateSQLPreview:l}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const u=[...s].sort((o,d)=>o.sequence-d.sequence),c=r.find(o=>o.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(n.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),u.map(o=>{const d=r.find(i=>i.name===o.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:o.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(n.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},o.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((u,c)=>u.sequence-c.sequence).map((u,c)=>{const o=r.find(x=>x.name===u.source.name),d=r.find(x=>x.name===u.target.name),i=u.joinKeyGroups.reduce((x,h)=>x+h.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(n.Badge,{variant:"outline",className:"shrink-0 text-xs",children:u.joinType}),e.jsxs(n.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[i," condition",i>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",d==null?void 0:d.name]})]},u.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:l()})})]})]})}function Ha({open:s,onOpenChange:a,variant:r="button"}={}){var A,B;const l=t.useEditorStore(S=>S.card),{autoJoinMetadata:u}=n.useEditorCardQuery(l),c=t.useEditorStore(S=>S.actions.updateCardConfig),o=((A=l==null?void 0:l.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,i]=C.useState(!1),x=s!==void 0,h=x?s:d,v=x?a:i,f=((B=l==null?void 0:l.dataSource)==null?void 0:B.selectedEntities)||[],m=S=>{c(l.id,{...l==null?void 0:l.config,joinPlan:S}),v(!1)},g=()=>{c(l.id,{...l==null?void 0:l.config,joinPlan:void 0})},y=()=>{v(!1)},b=()=>{const S=[...o.joins].sort((T,N)=>T.sequence-N.sequence),E=o.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
154
+ ON ${D}`}),N},isValidConfiguration:()=>!(!r.baseEntity.name||r.joins.some(M=>!M.source.name||!M.target.name)||r.joins.some(M=>M.joinKeyGroups.some(j=>j.keys.length===0))||r.joins.some(M=>M.joinKeyGroups.some(j=>j.keys.some(O=>!O.source.name||!O.target.name||!O.operator))))}}function Ka({joinPlan:s,availableDataSources:a,onSave:r,onRemove:l,onCancel:u}){const{setCardConfig:c}=t.useEditorActions();t.useEditorStore(D=>D.card.config);const{columnGroups:o}=n.useColumns(),d=o.filter(D=>D.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:i,expandedJoins:x,setJoinPlan:h,addJoin:v,removeJoin:f,updateJoin:m,moveJoinUp:g,moveJoinDown:y,toggleJoinExpansion:b,getAvailableSourceEntities:w,getAvailableTargetEntities:A,addJoinKeyGroup:B,updateGroupOperator:S,removeJoinKeyGroup:E,addJoinKey:I,updateJoinKey:T,removeJoinKey:N,generateSQLPreview:M,isValidConfiguration:j}=$a({initialJoinPlan:s,availableDataSources:a}),O=D=>{const L=d.find(R=>R.entityName===D);return(L==null?void 0:L.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:i.baseEntity.name,onValueChange:D=>{const L=a.find(R=>R.name===D);h({...i,baseEntity:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:D,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(D=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:M()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:v,children:[e.jsx(n.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.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:i.joins.map(D=>{const L=a.find(F=>F.name===D.source.name),R=a.find(F=>F.name===D.target.name),p=x.has(D.id);return e.jsxs(n.Card,{className:"border",children:[e.jsx(n.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{children:D.sequence}),e.jsxs(n.CardTitle,{className:"text-sm",children:["Join ",D.sequence,L&&R&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",L.name," → ",R.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===1,children:e.jsx(n.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(D.id),disabled:D.sequence===i.joins.length,children:e.jsx(n.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>b(D.id),children:p?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:()=>f(D.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),p&&e.jsxs(n.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:D.source.name,onValueChange:F=>{const k=a.find(P=>P.name===F);m(D.id,{source:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:F,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:w(D.id).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(n.Badge,{variant:"outline",className:"text-xs",children:F.type}),F.name]})},F.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:D.joinType,onValueChange:F=>m(D.id,{joinType:F}),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:D.target.name,onValueChange:F=>{const k=a.find(P=>P.name===F);m(D.id,{target:{connectionId:(k==null?void 0:k.connectionId)||"",connectionType:(k==null?void 0:k.connectionType)||"none",type:(k==null?void 0:k.type)||"table",name:F,database:k==null?void 0:k.database,schema:k==null?void 0:k.schema}})},disabled:!D.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:D.source.name?A(D.source.name).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(n.Badge,{variant:"outline",className:"text-xs",children:F.type}),F.name,F.name===D.source.name&&e.jsx(n.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},F.name)):[]})]})]})]}),D.source.name&&D.target.name&&L&&R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>B(D.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((F,k)=>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 ",k+1]}),k>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:F.operator,onValueChange:P=>S(D.id,k,P),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(D.id,k),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[F.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:F.keys.map((P,V)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[V>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:F.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.source.name,onValueChange:z=>T(D.id,k,V,"sourceColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:O(D.source.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:P.operator,onValueChange:z=>T(D.id,k,V,"operator",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:P.target.name,onValueChange:z=>T(D.id,k,V,"targetColumnName",z),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:O(D.target.name).map(z=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(n.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,k,V),children:e.jsx(t.X,{className:"size-3.5"})})]},P.id||V))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>I(D.id,k),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},F.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{l(),u()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:u,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>r(i),disabled:!j(),children:"Save"})]})]})}function Pn({children:s,open:a,onOpenChange:r,joinPlan:l,availableDataSources:u,onRemove:c,onSave:o,onCancel:d}){return e.jsxs(n.Dialog,{open:a,onOpenChange:r,children:[e.jsxs(n.DialogContent,{className:"max-w-4xl",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Join Configuration"}),e.jsx(n.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ka,{joinPlan:l,availableDataSources:u,onSave:o,onCancel:d,onRemove:c})]}),s]})}function Ga({joins:s,baseEntityId:a,availableDataSources:r,generateSQLPreview:l}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[s.length>0&&e.jsxs("div",{className:"px-4 py-2",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const u=[...s].sort((o,d)=>o.sequence-d.sequence),c=r.find(o=>o.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(n.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(n.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),u.map(o=>{const d=r.find(i=>i.name===o.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:o.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(n.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},o.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((u,c)=>u.sequence-c.sequence).map((u,c)=>{const o=r.find(x=>x.name===u.source.name),d=r.find(x=>x.name===u.target.name),i=u.joinKeyGroups.reduce((x,h)=>x+h.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(n.Badge,{variant:"outline",className:"shrink-0 text-xs",children:u.joinType}),e.jsxs(n.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[i," condition",i>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[o==null?void 0:o.name," → ",d==null?void 0:d.name]})]},u.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:l()})})]})]})}function Ua({open:s,onOpenChange:a,variant:r="button"}={}){var A,B;const l=t.useEditorStore(S=>S.card),{autoJoinMetadata:u}=n.useEditorCardQuery(l),c=t.useEditorStore(S=>S.actions.updateCardConfig),o=((A=l==null?void 0:l.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,i]=C.useState(!1),x=s!==void 0,h=x?s:d,v=x?a:i,f=((B=l==null?void 0:l.dataSource)==null?void 0:B.selectedEntities)||[],m=S=>{c(l.id,{...l==null?void 0:l.config,joinPlan:S}),v(!1)},g=()=>{c(l.id,{...l==null?void 0:l.config,joinPlan:void 0})},y=()=>{v(!1)},b=()=>{const S=[...o.joins].sort((T,N)=>T.sequence-N.sequence),E=o.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let I=`SELECT *
155
155
  FROM ${E.name}`;return S.forEach(T=>{const N=f.find(O=>O.name===T.target.name);if(!N)return;const M=T.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const D=O.keys.filter(L=>{var R,p,F,k;return((R=L.source)==null?void 0:R.name)&&((p=L.target)==null?void 0:p.name)&&((F=L.source)==null?void 0:F.entityName)&&((k=L.target)==null?void 0:k.entityName)}).map(L=>`${L.source.entityName}.${L.source.name} ${L.operator} ${L.target.entityName}.${L.target.name}`);return D.length>1?`(${D.join(` ${O.operator} `)})`:D[0]}).filter(Boolean),j=M.length>1?M.join(" OR "):M[0]||"condition_here";I+=`
156
156
  ${T.joinType} JOIN ${N.name}
157
- ON ${j}`}),I};if(f.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(Ua,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:f,generateSQLPreview:b})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:r==="badge"?e.jsxs(n.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:S=>{S.stopPropagation(),v(!0)},children:[e.jsx(n.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>v(!0),className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:o.joins.length===0?"Configure joins":`${o.joins.length} ${o.joins.length===1?"join":"joins"}`}),(u==null?void 0:u.autoResolved)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})}),w]})}),e.jsx(On,{open:h,onOpenChange:v,joinPlan:o,availableDataSources:f,onSave:m,onCancel:y,onRemove:g,children:e.jsx("div",{})})]})}function Qa(){var S,E,I,T,N,M;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),[u,c]=C.useState(!1),o=t.useEditorStore(j=>j.card.dataSource),d=t.useEditorStore(j=>j.card),i=t.useEditorStore(j=>j.isDevMode),{updateDataSource:x}=t.useEditorActions(),{autoJoinMetadata:h}=n.useEditorCardQuery(d),f={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]},m=n.toEntityArray(f.selectedEntities),g=m.length,y=g===0?"Choose dataset":g===1?ss(m[0]):`${g} datasets`,b=((I=(E=(S=d==null?void 0:d.config)==null?void 0:S.joinPlan)==null?void 0:E.joins)==null?void 0:I.length)??0,w=!!(h!=null&&h.autoResolved);((N=(T=h==null?void 0:h.resolvedJoinPlan)==null?void 0:T.joins)==null?void 0:N.length)??((M=h==null?void 0:h.relationshipsUsed)==null||M.length);const A=g<2?null:b>0?`${b} join${b===1?"":"s"}`:w?"auto":null,B=j=>{const O=m.filter(D=>!n.areContextEntitiesEqual(D,j));x({...f,selectedEntities:O})};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:s,onOpenChange:a,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:y}),A&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",A]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",s&&"rotate-180")})]})}),e.jsx(t.PopoverContent,{align:"start",sideOffset:4,className:"w-[320px] overflow-hidden rounded-control border border-border bg-popover p-0 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between px-3 pb-1.5 pt-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Datasets"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:g})]}),g===0?e.jsx("div",{className:"px-3 pb-2 text-[12px] text-muted-foreground",children:"No datasets selected."}):e.jsx("ul",{className:"mb-1",children:m.map((j,O)=>e.jsxs("li",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-muted/50",children:[e.jsx(n.Database,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[13px] text-foreground",children:ss(j)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Wa(j)})]}),e.jsx("button",{type:"button",onClick:()=>B(j),"aria-label":`Remove ${ss(j)}`,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]},`${j.connectionId}-${j.name}-${O}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),l(!0)},className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground",children:[e.jsx(n.Plus,{className:"h-3 w-3"}),"Add dataset"]})]}),g>1&&!i&&e.jsxs("div",{className:"border-t border-border/60 px-3 py-2.5",children:[e.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join"})}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),c(!0)},className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:b>0?`${b} ${b===1?"join":"joins"}`:"Configure joins"}),w&&b===0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})]}),e.jsx("div",{className:"flex items-center justify-end border-t border-border/60 px-2 py-1.5",children:e.jsx("button",{type:"button",onClick:()=>a(!1),className:"inline-flex h-6 items-center rounded-control px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Done"})})]})})]}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:r,onOpenChange:l,dataSource:f}),g>1&&!i&&e.jsx("div",{className:"hidden",children:e.jsx(Ha,{open:u,onOpenChange:c})})]})}function ss(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function Wa(s){const a=[];return s.connectionType&&a.push(String(s.connectionType)),s.database&&a.push(s.database),s.schema&&a.push(s.schema),a.join(" · ")}function Pn({isVisible:s}){n.useSyncLegacyEditorState();const[a,r]=C.useState(!1);return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",{"w-[290px]":s,"min-w-[290px]":s,"w-0 border-r-0":!s,"min-w-0":!s}),children:[e.jsx("div",{className:"px-4 pt-4",children:e.jsx(Qa,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(n.FieldsSection,{})}),e.jsx($a,{open:a,onOpenChange:r})]})}const Ja=300;function Ya(){const s=t.useEditorStore(w=>w.card.sql),a=t.useEditorStore(w=>w.sqlGen),r=t.useEditorStore(w=>w.card),l=Me.useEffectiveEditorCardType(),{setCardSql:u,setSqlGen:c,setRunSql:o}=t.useEditorActions(),d=C.useMemo(()=>l!==r.type?{...r,type:l}:r,[r,l]),{queryKey:i}=n.useEditorCardQuery(d),x=n.useQueryClient(),h=C.useRef(i);h.current=i;const v=C.useRef(a);v.current=a;const f=C.useCallback(w=>{u(w)},[u]),{value:m,onChange:g,flush:y}=Rn({storeValue:s,defaultValue:"",onStoreUpdate:f,delay:Ja});C.useEffect(()=>ct.registerPendingEditorDraftFlusher(y),[y]);function b(w){g(w),t.isObjectEmpty(v.current)||c({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!m&&e.jsx("div",{className:"pointer-events-none absolute left-[56px] top-4 z-10 font-mono text-[12px] leading-[1.55] text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.CodeEditor,{value:m??"",onValueChange:b,language:"sql-jinja",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:w=>{w.key==="Enter"&&w.shiftKey&&(w.preventDefault(),ct.flushPendingEditorDrafts(),setTimeout(()=>{x.removeQueries({queryKey:h.current,exact:!0}),o(!0)},0))}})]})}const Xa=300;function Za(){const s=t.useEditorStore(f=>f.card.python),a=t.useEditorStore(f=>f.card),r=Me.useEffectiveEditorCardType(),{setCardPython:l,setRunSql:u}=t.useEditorActions(),c=C.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:o}=n.useEditorCardQuery(c),d=n.useQueryClient(),i=C.useRef(o);i.current=o;const{value:x,onChange:h,flush:v}=Rn({storeValue:s,defaultValue:n.PYTHON_DEFAULT_CODE,onStoreUpdate:l,delay:Xa});return C.useEffect(()=>ct.registerPendingEditorDraftFlusher(v),[v]),e.jsx(t.CodeEditor,{value:x??"",onValueChange:h,language:"python",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:f=>{f.key==="Enter"&&f.shiftKey&&(f.preventDefault(),ct.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:i.current,exact:!0}),u(!0)},0))}})}const er=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,tr=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,sr=/\bwhere\b/i;function nr(s){return s!=null&&s.trim()?er.test(s)||tr.test(s):!1}function ar(s){return!(s!=null&&s.trim())||nr(s)?null:sr.test(s)?{helper:"{{ filters | and }}",description:"Use this inside your existing WHERE clause to append dashboard filters."}:{helper:"{{ filters | where }}",description:"Use this when the query does not already have a WHERE clause."}}function rr(s){const{request:a,mode:r="draft",currentSql:l,selectedTableName:u,selectedSchemaName:c,selectedDatabaseName:o}=s,d=[o?`Database: ${o}`:"",c?`Schema: ${c}`:"",u?`Table: ${u}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${n.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",r==="refine"&&l?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
157
+ ON ${j}`}),I};if(f.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(Ga,{joins:o.joins,baseEntityId:o.baseEntity.name,availableDataSources:f,generateSQLPreview:b})});return e.jsxs(e.Fragment,{children:[e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:r==="badge"?e.jsxs(n.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:S=>{S.stopPropagation(),v(!0)},children:[e.jsx(n.Link,{className:"h-3 w-3"}),o.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>v(!0),className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:o.joins.length===0?"Configure joins":`${o.joins.length} ${o.joins.length===1?"join":"joins"}`}),(u==null?void 0:u.autoResolved)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})}),w]})}),e.jsx(Pn,{open:h,onOpenChange:v,joinPlan:o,availableDataSources:f,onSave:m,onCancel:y,onRemove:g,children:e.jsx("div",{})})]})}function Ha(){var S,E,I,T,N,M;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),[u,c]=C.useState(!1),o=t.useEditorStore(j=>j.card.dataSource),d=t.useEditorStore(j=>j.card),i=t.useEditorStore(j=>j.isDevMode),{updateDataSource:x}=t.useEditorActions(),{autoJoinMetadata:h}=n.useEditorCardQuery(d),f={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]},m=n.toEntityArray(f.selectedEntities),g=m.length,y=g===0?"Choose dataset":g===1?ss(m[0]):`${g} datasets`,b=((I=(E=(S=d==null?void 0:d.config)==null?void 0:S.joinPlan)==null?void 0:E.joins)==null?void 0:I.length)??0,w=!!(h!=null&&h.autoResolved);((N=(T=h==null?void 0:h.resolvedJoinPlan)==null?void 0:T.joins)==null?void 0:N.length)??((M=h==null?void 0:h.relationshipsUsed)==null||M.length);const A=g<2?null:b>0?`${b} join${b===1?"":"s"}`:w?"auto":null,B=j=>{const O=m.filter(D=>!n.areContextEntitiesEqual(D,j));x({...f,selectedEntities:O})};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:s,onOpenChange:a,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:y}),A&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",A]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",s&&"rotate-180")})]})}),e.jsx(t.PopoverContent,{align:"start",sideOffset:4,className:"w-[320px] overflow-hidden rounded-control border border-border bg-popover p-0 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between px-3 pb-1.5 pt-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Datasets"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:g})]}),g===0?e.jsx("div",{className:"px-3 pb-2 text-[12px] text-muted-foreground",children:"No datasets selected."}):e.jsx("ul",{className:"mb-1",children:m.map((j,O)=>e.jsxs("li",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-muted/50",children:[e.jsx(n.Database,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[13px] text-foreground",children:ss(j)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Qa(j)})]}),e.jsx("button",{type:"button",onClick:()=>B(j),"aria-label":`Remove ${ss(j)}`,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]},`${j.connectionId}-${j.name}-${O}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),l(!0)},className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground",children:[e.jsx(n.Plus,{className:"h-3 w-3"}),"Add dataset"]})]}),g>1&&!i&&e.jsxs("div",{className:"border-t border-border/60 px-3 py-2.5",children:[e.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join"})}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),c(!0)},className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted focus:outline-none focus-visible:border-ring",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:b>0?`${b} ${b===1?"join":"joins"}`:"Configure joins"}),w&&b===0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Sparkles,{className:"h-3 w-3",strokeWidth:1.75}),"Auto"]})]})]}),e.jsx("div",{className:"flex items-center justify-end border-t border-border/60 px-2 py-1.5",children:e.jsx("button",{type:"button",onClick:()=>a(!1),className:"inline-flex h-6 items-center rounded-control px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Done"})})]})})]}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:r,onOpenChange:l,dataSource:f}),g>1&&!i&&e.jsx("div",{className:"hidden",children:e.jsx(Ua,{open:u,onOpenChange:c})})]})}function ss(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function Qa(s){const a=[];return s.connectionType&&a.push(String(s.connectionType)),s.database&&a.push(s.database),s.schema&&a.push(s.schema),a.join(" · ")}function Bn({isVisible:s}){n.useSyncLegacyEditorState();const[a,r]=C.useState(!1);return e.jsxs("div",{className:t.cn("flex shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",{"w-[290px]":s,"min-w-[290px]":s,"w-0 border-r-0":!s,"min-w-0":!s}),children:[e.jsx("div",{className:"px-4 pt-4",children:e.jsx(Ha,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(n.FieldsSection,{})}),e.jsx(qa,{open:a,onOpenChange:r})]})}const Wa=300;function Ja(){const s=t.useEditorStore(w=>w.card.sql),a=t.useEditorStore(w=>w.sqlGen),r=t.useEditorStore(w=>w.card),l=Me.useEffectiveEditorCardType(),{setCardSql:u,setSqlGen:c,setRunSql:o}=t.useEditorActions(),d=C.useMemo(()=>l!==r.type?{...r,type:l}:r,[r,l]),{queryKey:i}=n.useEditorCardQuery(d),x=n.useQueryClient(),h=C.useRef(i);h.current=i;const v=C.useRef(a);v.current=a;const f=C.useCallback(w=>{u(w)},[u]),{value:m,onChange:g,flush:y}=On({storeValue:s,defaultValue:"",onStoreUpdate:f,delay:Wa});C.useEffect(()=>ct.registerPendingEditorDraftFlusher(y),[y]);function b(w){g(w),t.isObjectEmpty(v.current)||c({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!m&&e.jsx("div",{className:"pointer-events-none absolute left-[56px] top-4 z-10 font-mono text-[12px] leading-[1.55] text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.CodeEditor,{value:m??"",onValueChange:b,language:"sql-jinja",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:w=>{w.key==="Enter"&&w.shiftKey&&(w.preventDefault(),ct.flushPendingEditorDrafts(),setTimeout(()=>{x.removeQueries({queryKey:h.current,exact:!0}),o(!0)},0))}})]})}const Ya=300;function Xa(){const s=t.useEditorStore(f=>f.card.python),a=t.useEditorStore(f=>f.card),r=Me.useEffectiveEditorCardType(),{setCardPython:l,setRunSql:u}=t.useEditorActions(),c=C.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:o}=n.useEditorCardQuery(c),d=n.useQueryClient(),i=C.useRef(o);i.current=o;const{value:x,onChange:h,flush:v}=On({storeValue:s,defaultValue:n.PYTHON_DEFAULT_CODE,onStoreUpdate:l,delay:Ya});return C.useEffect(()=>ct.registerPendingEditorDraftFlusher(v),[v]),e.jsx(t.CodeEditor,{value:x??"",onValueChange:h,language:"python",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:f=>{f.key==="Enter"&&f.shiftKey&&(f.preventDefault(),ct.flushPendingEditorDrafts(),setTimeout(()=>{d.removeQueries({queryKey:i.current,exact:!0}),u(!0)},0))}})}const Za=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,er=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,tr=/\bwhere\b/i;function sr(s){return s!=null&&s.trim()?Za.test(s)||er.test(s):!1}function nr(s){return!(s!=null&&s.trim())||sr(s)?null:tr.test(s)?{helper:"{{ filters | and }}",description:"Use this inside your existing WHERE clause to append dashboard filters."}:{helper:"{{ filters | where }}",description:"Use this when the query does not already have a WHERE clause."}}function ar(s){const{request:a,mode:r="draft",currentSql:l,selectedTableName:u,selectedSchemaName:c,selectedDatabaseName:o}=s,d=[o?`Database: ${o}`:"",c?`Schema: ${c}`:"",u?`Table: ${u}`:""].filter(Boolean);return["You are an expert SQL writing assistant embedded in a query editor.",`Write SQL only. You may call only read-only tools when needed: ${n.INLINE_ALLOWED_TOOL_LIST}.`,"Do not call mutation tools or chart-creation tools; those require Full Assistant.","Return exactly one SQL statement inside a single ```sql fenced block.","After the code block, optionally include one short sentence.",r==="refine"&&l?"Mode: Refine existing SQL. Keep the current query structure and only apply the requested changes unless the current query is invalid.":"Mode: Draft new SQL from the request.",d.length>0?`Context:
158
158
  ${d.join(`
159
159
  `)}`:"",l?r==="refine"?`Current SQL (must refine):
160
160
  ${l}`:`Current SQL (revise if useful):
161
161
  ${l}`:"",`User request:
162
162
  ${a}`].filter(Boolean).join(`
163
163
 
164
- `)}function lr(s){const{request:a,failedSql:r,errorMessage:l,errorCode:u,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,contextEntityLabels:i}=s,x=[c?`Database: ${c}`:"",o?`Schema: ${o}`:"",d?`Table: ${d}`:"",i.length>0?`Selected context entities: ${i.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",x.length>0?`Context:
164
+ `)}function rr(s){const{request:a,failedSql:r,errorMessage:l,errorCode:u,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,contextEntityLabels:i}=s,x=[c?`Database: ${c}`:"",o?`Schema: ${o}`:"",d?`Table: ${d}`:"",i.length>0?`Selected context entities: ${i.join(", ")}`:""].filter(Boolean);return["You are fixing SQL after validation failed.","Return one read-only SQL statement in a single ```sql fenced block.","Do not call mutation tools.",x.length>0?`Context:
165
165
  ${x.join(`
166
166
  `)}`:"",`Original user request:
167
167
  ${a}`,`Previous SQL draft:
168
168
  ${r}`,`Validation failure${u?` (${u})`:""}:
169
169
  ${l}`].filter(Boolean).join(`
170
170
 
171
- `)}function or(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const ns={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function ir(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 cn(s){let a=0;for(let r=0;r<s.length;r+=1)a=(a<<5)-a+s.charCodeAt(r),a|=0;return String(a)}function dn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function cr(s,a){return s===n.SELF_HEAL_TIMELINE_STEP&&a>0?`${n.SELF_HEAL_TIMELINE_STEP} ${a}/${n.MAX_SELF_HEAL_ATTEMPTS}`:s}function Bt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function un(s){var a;for(let r=s.length-1;r>=0;r-=1){const l=s[r];if(l.role!=="user")continue;const u=(a=l.metadata)==null?void 0:a.inlineRunToken;if(typeof u=="string"&&u.length>0)return u}}function dr(s){if(!s)return"";const a=s.trim(),r=s.match(/```sql\s*([\s\S]*?)```/i);if(r!=null&&r[1])return r[1].trim();const l=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return l!=null&&l[1]?l[1].trim():/^(select|with|insert|update|delete)\b/i.test(a)?a:""}function mn(s){for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(!(r.role!=="assistant"||!Array.isArray(r.parts)))for(let l=r.parts.length-1;l>=0;l-=1){const u=r.parts[l];if((u==null?void 0:u.type)!=="text"||typeof(u==null?void 0:u.text)!="string")continue;const c=dr(u.text);if(c)return c}}return""}function ur({currentSql:s,currentPython:a,selectedDatabaseName:r,selectedSchemaName:l,selectedTableName:u,onApplySql:c,onOpenFullAssistant:o}){var Rt,St;const{authToken:d,tokenProps:i}=n.useSemaphorContext(),x=(Rt=n.useDashboardQuery().data)==null?void 0:Rt.assistantProfileId,h=t.useEditorStore(G=>G.isDevMode),v=t.useEditorStore(G=>G.selectedConnectionId),f=t.useEditorStore(G=>{var X;return(X=G.card.dataSource)==null?void 0:X.selectedEntities}),m=t.useAIInteractionStore(G=>G.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:y}=t.useAIActions(),[b,w]=C.useState(""),[A,B]=C.useState(""),[S,E]=C.useState(""),[I,T]=C.useState("draft"),[N,M]=C.useState("draft"),[j,O]=C.useState(""),[D,L]=C.useState(!1),[R,p]=C.useState({status:"idle"}),[F,k]=C.useState(ns),[P,V]=C.useState(!1),[z,_]=C.useState(()=>Bt("inline-query-session")),q=C.useRef(null),W=C.useRef(null),$=C.useRef(null),U=C.useRef(0),se=C.useRef(0),ie=C.useRef(Bt("inline-run-token")),le=C.useRef(z),de=C.useRef(new Set),me=C.useRef(new Map),ue=C.useRef(0),Ne=C.useRef(""),we=C.useRef(!1),Te=C.useRef(!1),Z=C.useRef(ns),je=C.useRef(!1),Ie=C.useRef(null),ne=C.useRef(()=>{}),Ae=(St=i.apiServiceUrl)==null?void 0:St.replace(/\/$/,""),Le=Ae?`${Ae}/v1/sql/validate`:"/v1/sql/validate",ae=C.useCallback(G=>{k(X=>{const J=G(X);return Z.current=J,J})},[]),ve=C.useCallback((G,X)=>{ae(J=>J.runId===G?X(J):J)},[ae]),ye=C.useCallback(G=>se.current===G&&!de.current.has(G),[]),K=C.useCallback((G,X,J)=>{ve(G,ce=>{const ge=ce.timelineSteps.includes(X)?ce.timelineSteps:[...ce.timelineSteps,X];return{...ce,phase:(J==null?void 0:J.phase)||ce.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:ce.attempt,activeStep:X,timelineSteps:ge,finalOutcome:(J==null?void 0:J.finalOutcome)||ce.finalOutcome,hasTools:J!=null&&J.hasTools?!0:ce.hasTools}})},[ve]),Q=C.useCallback(()=>{const G=se.current+1,X=Bt("inline-run-token"),J=Bt("inline-query-session");return se.current=G,ie.current=X,le.current=J,_(J),de.current=new Set,me.current=new Map,ue.current=0,Ne.current="",je.current=!1,ae(()=>({runId:G,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:G,runToken:X,chatSessionId:J}},[ae]),te=C.useCallback(()=>{if(we.current||Te.current||g>0)return;const G=f||[];if(G.length===0)return;const X=t.useAIInteractionStore.getState().currentAIContext;y({...X,selectedEntities:G}),Te.current=!0},[g,f,y]),xe=C.useCallback(()=>{we.current=!0},[]),pe=C.useCallback((G,X,J)=>{or(G,{runId:X,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:ue.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:F.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||F.finalOutcome})},[g,F.finalOutcome,F.hasTools]),Fe=C.useCallback((G,X)=>{const J=$.current;if(!J)return;const ce={inlineRunToken:X};J({role:"user",parts:[{type:"text",text:G}],metadata:ce},{metadata:ce})},[]);C.useEffect(()=>{const G=Ie.current;!G||G.sessionId!==z||(Ie.current=null,Fe(G.message,G.runToken))},[z,Fe]);const ee=z,Se=C.useCallback(async({toolCall:G})=>{var Ve,Xe,lt,nt,_e,gt;if(ee!==le.current)return;const X=String(G.toolName||"").trim();if(!X)return;const J=se.current;if(!ye(J)){(Ve=W.current)==null||Ve.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(X==="getUserSql"){K(J,dn(X),{hasTools:!0}),pe("inline_tool_step",J,{hasTools:!0}),(Xe=W.current)==null||Xe.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const ce=n.INLINE_BLOCKED_MUTATING_TOOLS.has(X),ge=n.INLINE_ALLOWED_READ_ONLY_TOOLS.has(X);if(ce||!ge){(lt=W.current)==null||lt.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const be=dn(X);K(J,be,{phase:F.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),pe("inline_tool_step",J,{hasTools:!0});const Pe=((nt=G.input)==null?void 0:nt.sql)??((_e=G.args)==null?void 0:_e.sql);typeof Pe=="string"&&Pe.trim().length>0&&(je.current=!1,E(Pe.trim())),(gt=W.current)==null||gt.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,pe,F.phase,ye,ee,K]),fe=C.useCallback(({message:G,messages:X})=>{if(ee!==le.current)return;const J=un(X);if(!J||J!==ie.current)return;const ce=se.current;if(!ye(ce))return;const ge=mn([G])||mn(X);if(ge){je.current=!1,E(ge.trim());return}je.current&&Z.current.phase==="self-healing"&&ne.current(ce)},[ye,ee]),De=C.useCallback(G=>{if(ee!==le.current)return;const X=se.current;ye(X)&&je.current&&Z.current.phase==="self-healing"&&ne.current(X)},[ye,ee]),{setMessages:Oe,sendMessage:Qe,addToolResult:Ke,status:Ge,stop:re,error:ke,clearError:ze}=n.useChat({id:z,transport:new n.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const G=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:h,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:X,requestMetadata:J})=>{const ce=J==null?void 0:J.inlineRunToken,ge=un(G);return{body:{...X,inlineRunToken:ce||ge,messages:t.cleanupIncompleteMessages(G)}}}}),onToolCall:Se,onFinish:fe,onError:De,sendAutomaticallyWhen:n.lastAssistantMessageIsCompleteWithToolCalls});W.current=Ke,$.current=Qe;const Ce=!["ready","error"].includes(Ge),We=(ke==null?void 0:ke.message)||"Unable to generate a SQL draft right now. Try again.",Ee=C.useCallback(G=>{const X=se.current,J=Z.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){G==="stopped"&&Ce&&re();return}de.current.add(X),je.current=!1,U.current+=1,Ne.current="",p({status:"idle"}),E(""),ze(),Oe([]),ve(X,ge=>({...ge,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),pe("inline_self_heal_stopped",X,{finalOutcome:"cancelled"}),(Ce||G==="stopped")&&re()},[ze,pe,Ce,Oe,re,ve]),yt=C.useCallback(async(G,X)=>{var ce;if(!ye(X))return null;const J=U.current+1;U.current=J,K(X,"Validating SQL",{phase:"validating"}),p({status:"validating"});try{const ge=await t.postRequestRegular(Le,(d==null?void 0:d.accessToken)||"",{sql:G,connectionId:v||void 0});if(U.current!==J||!ye(X))return null;if((ge==null?void 0:ge.valid)===!0)return p({status:"valid",message:"SQL validation passed."}),ve(X,Ve=>({...Ve,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),pe("inline_draft_validated",X,{finalOutcome:"validated"}),{status:"valid"};const be=ir(ge==null?void 0:ge.errorCode)||"UNKNOWN",Pe=typeof(ge==null?void 0:ge.error)=="string"&&ge.error||typeof((ce=ge==null?void 0:ge.details)==null?void 0:ce.error)=="string"&&ge.details.error||"SQL validation failed. Please revise the query draft.";return p({status:"invalid",message:Pe,errorCode:be}),ve(X,Ve=>({...Ve,lastValidation:{valid:!1,error:Pe,errorCode:be}})),pe("inline_validation_failed",X,{errorCode:be,finalOutcome:"validation_failed"}),{status:"invalid",error:Pe,errorCode:be}}catch(ge){if(U.current!==J||!ye(X))return null;const be=t.getRequestErrorMessage(ge,"Validation service unavailable. You can still replace and run.");return p({status:"error",message:be,errorCode:"SQL_CONNECTION_ERROR"}),ve(X,Pe=>({...Pe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:be,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:be,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,pe,ye,v,Le,ve,K]),Ze=C.useCallback((G,X,J,ce)=>{let ge=J,be="validation_failed",Pe="Validating SQL";X==="attempt_limit"?(ge=`Couldn't auto-fix after ${n.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,be="self_heal_exhausted",Pe=`Auto-fix stopped (${n.MAX_SELF_HEAL_ATTEMPTS} attempts)`):X==="duplicate"&&(ge=`Auto-fix stopped (repeated validation failure). ${J}`,be="self_heal_duplicate_stopped",Pe="Auto-fix stopped (repeated failure)"),p({status:"invalid",message:ge,errorCode:ce}),K(G,Pe,{phase:"error",finalOutcome:be}),ve(G,Ve=>({...Ve,phase:"error",finalOutcome:be,lastValidation:{valid:!1,error:ge,errorCode:ce}})),X!=="terminal"&&pe("inline_self_heal_stopped",G,{errorCode:ce,finalOutcome:be}),je.current=!1},[pe,ve,K]),kt=C.useCallback(G=>{const X="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";p({status:"invalid",message:X,errorCode:"UNKNOWN"}),K(G,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),ve(G,ce=>({...ce,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:X,errorCode:"UNKNOWN"}})),pe("inline_self_heal_stopped",G,{errorCode:"UNKNOWN",finalOutcome:J}),je.current=!1},[pe,ve,K]);ne.current=kt,C.useEffect(()=>{const G=S.trim(),X=se.current;if(!G){if(U.current+=1,Ne.current="",Z.current.phase==="error")return;p({status:"idle"});return}if(!ye(X)||Ce)return;const J=`${X}:${ue.current}:${cn(G)}`;if(Ne.current===J)return;Ne.current=J;let ce=!1;return(async()=>{const be=await yt(G,X);if(!be||ce||!ye(X)||be.status!=="invalid")return;if(!n.RECOVERABLE_SQL_ERROR_CODES.has(be.errorCode)){Ze(X,"terminal",be.error,be.errorCode);return}const Pe=`${cn(G)}::${be.errorCode}`,Ve=(me.current.get(Pe)||0)+1;if(me.current.set(Pe,Ve),Ve>=2){Ze(X,"duplicate",be.error,be.errorCode);return}if(ue.current>=n.MAX_SELF_HEAL_ATTEMPTS){Ze(X,"attempt_limit",be.error,be.errorCode);return}const Xe=ue.current+1;ue.current=Xe,K(X,n.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Xe}),pe("inline_self_heal_attempt",X,{attemptCount:Xe,errorCode:be.errorCode}),je.current=!0,ze(),Oe([]),E("");const lt=m.map(_e=>{const gt=_e!=null&&_e.database?`${_e.database}.`:"",Xt=_e!=null&&_e.schema?`${_e.schema}.`:"",Zt=(_e==null?void 0:_e.name)||"unknown";return`${gt}${Xt}${Zt}`}),nt=lr({request:A,failedSql:G,errorMessage:be.error,errorCode:be.errorCode,selectedDatabaseName:r||"",selectedSchemaName:l||"",selectedTableName:u||"",contextEntityLabels:lt});Fe(nt,ie.current)})(),()=>{ce=!0}},[ze,m,pe,Ce,ye,A,S,r,l,u,Fe,Oe,Ze,K,yt]);const Je=(s==null?void 0:s.trim())||"",Dt=C.useCallback((G="draft")=>{if(Ce)return;const X=b.trim();if(!X)return;const J=G==="refine"&&Je?"refine":"draft",ce=J==="refine"?Je:"",ge=Je,{runId:be,runToken:Pe,chatSessionId:Ve}=Q();pe("inline_draft_started",be,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),te(),ze(),B(X),E(""),T(J),O(ce),L(!1),p({status:"idle"}),U.current+=1,Oe([]),V(!0);const Xe=rr({request:X,mode:J,currentSql:ge,selectedTableName:u||"",selectedSchemaName:l||"",selectedDatabaseName:r||""});Ie.current={sessionId:Ve,message:Xe,runToken:Pe}},[Q,ze,Je,pe,Ce,b,te,r,l,u,Oe]),dt=C.useCallback(G=>{const X=S.trim();X&&(c(X,G),G||V(!1))},[c,S]),et=S.trim().length>0,At=["valid","invalid","error"].includes(R.status),Nt=et&&At,Ht=R.status==="invalid",Mt=R.status==="validating",ut=et&&A.length>0&&A===b.trim(),mt=Je.length>0,xt=b.length>0,ht=ut&&I==="draft",Ue=ut&&I==="refine"&&j===Je,tt=N==="refine"&&!mt?"draft":N,st=(tt==="refine"?Ue:ht)?"Open composer preview":"Generate composer SQL",Lt=b.trim().length>0||A.trim().length>0||et||R.status!=="idle"||F.timelineSteps.length>0,Ct=C.useCallback((G="draft")=>{if(Ce)return;if((G==="refine"?Ue:ht)&&!P){te(),V(!0);return}Dt(G)},[ht,Ue,Dt,Ce,P,te]),pt=C.useCallback(()=>{te(),V(!0)},[te]),Wt=C.useCallback(G=>{Ee("cancelled"),w(G)},[Ee]),Jt=C.useCallback(()=>{Ce||(Ee("cancelled"),je.current=!1,U.current+=1,Ne.current="",ue.current=0,w(""),B(""),E(""),T("draft"),M("draft"),O(""),L(!1),p({status:"idle"}),ze(),Oe([]),ae(G=>({...ns,runId:G.runId})))},[Ee,ze,Ce,Oe,ae]),Yt=C.useCallback(G=>{G||Ee("cancelled"),V(G)},[Ee]),He=F.timelineSteps.findIndex(G=>G===F.activeStep),Ft=F.phase==="self-healing"?"Fixing validation issue":F.phase==="validating"?"Validating SQL":F.activeStep||"Drafting SQL",ft=R.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:R.message}:R.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:R.message}:R.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:R.message}:null;return e.jsxs("div",{ref:q,className:"relative flex h-7 min-w-[320px] flex-1 items-center",children:[e.jsx(n.Sparkles,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground",strokeWidth:1.75}),e.jsx(t.Input,{value:b,onChange:G=>Wt(G.target.value),onFocus:pt,onClick:pt,onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),Ct(tt))},placeholder:"Ask in plain English — e.g. top 10 customers by profit last quarter",className:["h-7 rounded-[5px] border border-border/60 bg-background pl-7 text-[12px] shadow-none placeholder:text-muted-foreground/70 focus-visible:border-ring focus-visible:ring-0",xt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:P,onOpenChange:Yt,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:[xt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),Ee("cancelled"),w("")},disabled:Ce,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),Ct(tt)},disabled:Ce,"aria-label":st,title:st,children:e.jsx(Fa,{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:G=>{G.preventDefault()},onInteractOutside:G=>{var J;const X=G.target;X&&((J=q.current)!=null&&J.contains(X))&&G.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-[5px] border border-border/60 bg-background p-0.5",children:[e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",tt==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{M("draft"),L(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",tt==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>M("refine"),disabled:!mt,children:"Refine"})]}),e.jsx(n.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:xe})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{Ee("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Jt,disabled:!Lt,children:"Clear"})]})]}),F.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[F.timelineSteps.map((G,X)=>{const J=G===F.activeStep&&["drafting","validating","self-healing"].includes(F.phase),ce=!J&&He>=0&&X<He;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":ce?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:cr(G,F.attempt)},`${G}-${X}`)}),ft&&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]",ft.className].join(" "),children:ft.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:ft.detail})]})})]}),(Ce||F.phase==="self-healing"||R.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"}),Ft]}),ke&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:We}),I==="refine"&&j&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-[5px] border border-border/60 bg-muted/20 px-2.5 py-1.5 text-[11px]",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"xs",onClick:()=>L(G=>!G),children:D?"Hide base SQL":"View base SQL"})]}),D&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:j,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Base SQL"})})]}),Nt?e.jsxs("div",{className:"space-y-1",children:[I==="refine"&&e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:S,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Drafted SQL"})})]}):et?e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:"Validating SQL draft before preview."}):!Ce&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:mt?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:o,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:Ce||!Nt,onClick:()=>dt(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!Nt||Mt||Ht,onClick:()=>dt(!0),children:"Replace & Run"})]})]})})]})]})}function mr(){var we,Te;const s=n.useQueryClient(),[a,r]=C.useState(!1),l=t.useEditorStore(Z=>Z.frame),u=t.useEditorStore(Z=>Z.card);t.useEditorStore(Z=>Z.isShowingVisual),t.useEditorStore(Z=>Z.selectedConnectionId),t.useEditorStore(Z=>Z.tempQueryData);const c=t.useEditorStore(Z=>Z.selectedDatabaseName);t.useEditorStore(Z=>Z.selectedDatamodelId);const o=t.useEditorStore(Z=>Z.selectedSchemaName);t.useEditorStore(Z=>Z.showAIDialog);const d=t.useEditorStore(Z=>Z.selectedTableName),i=t.useDashboardStore(Z=>{var je,Ie;return((Ie=(je=Z.dashboard)==null?void 0:je.filters)==null?void 0:Ie.length)??0}),x=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(u==null?void 0:u.id)??""]),h=C.useMemo(()=>n.findCustomVisualConfigCard(l,u),[l,u]),{manifest:v}=n.useCustomVisual(((we=h==null?void 0:h.customCardPreferences)==null?void 0:we.url)||""),f=C.useMemo(()=>{var Z;return(Z=v==null?void 0:v.visuals)==null?void 0:Z.find(je=>{var Ie;return je.name===((Ie=h==null?void 0:h.customCardPreferences)==null?void 0:Ie.componentName)})},[v,(Te=h==null?void 0:h.customCardPreferences)==null?void 0:Te.componentName]),m=n.resolveMultiInputType(h,f),g=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:h,isMultiInputVisual:m==="multiple"}),[l,h,m]),y=C.useMemo(()=>{const Z=g.findIndex(je=>(je==null?void 0:je.id)===(u==null?void 0:u.id));return Z<0?-1:n.getSlotIndexForCard(u,Z)},[g,u]),b=C.useMemo(()=>!h||m!=="multiple"||y<0?u.type:n.getEffectiveCardTypeForSlot(u,y,f==null?void 0:f.slots)??u.type,[h,m,y,u,f==null?void 0:f.slots]),w=C.useMemo(()=>b!==u.type?{...u,type:b}:u,[u,b]),A=C.useMemo(()=>i===0?null:ar(u==null?void 0:u.sql),[u==null?void 0:u.sql,i]),B=C.useRef(!0),{setCardCustomCfg:S,setQueryResultColumns:E,setCardSql:I,setTempQueryData:T,setPythonStdOut:N,setCardPreferences:M,setCardType:j,setCardPython:O,setShowAIDialog:D,setCard:L,updateCardInFrame:R}=t.useEditorActions();t.useEditorStore(Z=>Z.onSave),t.useEditorStore(Z=>Z.onClose),t.useEditorStore(Z=>Z.actions.setSqlGen);const p=t.useEditorStore(Z=>Z.runSql),F=t.useEditorStore(Z=>Z.actions.setRunSql),k=t.useEditorStore(Z=>Z.actions.setIsSqlRunning),{data:P,isLoading:V,isFetching:z,isSuccess:_,isError:q,error:W,errorSql:$,queryKey:U,refetch:se,errorMessage:ie}=n.useEditorCardQuery(w),le=C.useRef(U);le.current=U,C.useEffect(()=>{if(P&&(P.rowLimitExceeded&&n.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),N((P==null?void 0:P.output)||""),P.records.length>0)){const{dimensionKeys:Z}=n.getKeys(P.records);E(Z)}},[P,E,N]),C.useEffect(()=>{(V||z)&&k(!0),(q||_)&&k(!1),q&&(E([]),N(""))},[V,z,P,N,q,_,k,E,W]),C.useEffect(()=>{p&&(s.getQueryData(U)||se(),F(!1))},[p,se,F,U,s]);const de=C.useRef(se);de.current=se,C.useEffect(()=>{if(B.current){B.current=!1;return}de.current()},[x]);function me(Z,je){I(Z),je&&F(!0)}function ue(){return e.jsxs(n.ResizablePanelGroup,{className:"flex grow gap-2 px-4",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(n.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-full overflow-hidden rounded-control border border-border bg-background",children:e.jsx(Ya,{})}),a&&e.jsx("code",{className:"absolute right-3 top-2 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs(n.PanelResizeHandle,{className:"group/divider relative my-1 flex h-6 w-full shrink-0 cursor-row-resize items-center gap-3 px-1 outline-none",children:[e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(n.ArrowDown,{className:"h-3 w-3",strokeWidth:1.75}),"Post-process with Python"]}),e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsx("button",{type:"button","aria-label":"Close Python editor",onClick:Z=>{Z.stopPropagation(),r(!1)},onPointerDown:Z=>Z.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3",strokeWidth:1.75})})]}),e.jsx(n.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:e.jsxs("div",{id:"python-container",className:"relative flex w-full flex-col overflow-hidden rounded-control border border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30 px-3 py-1.5 text-[11px] text-muted-foreground",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"rounded-control bg-background px-1.5 py-0.5 font-mono text-[10px] text-foreground/80",children:"Py"}),e.jsx("code",{className:"truncate font-mono text-[11px] text-foreground/80",children:"def process(df) → df"}),e.jsx("span",{className:"hidden truncate text-muted-foreground/80 sm:inline",children:"Runs after SQL · receives a DataFrame"})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Python 3.11"})]}),e.jsx("div",{className:"relative flex flex-1",children:e.jsx(Za,{})})]})})]})]})}function Ne(){return e.jsxs("div",{role:"editor-controls",className:"flex w-full flex-wrap items-center gap-2 px-4 pb-2 pt-3",children:[A&&e.jsxs("div",{className:"mb-1.5 mr-6 flex w-full items-center gap-1.5 px-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Filter,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Not subscribed to dashboard filters. Add"," ",e.jsx("button",{type:"button",title:"Click to copy",onClick:()=>{var Z;typeof navigator>"u"||!((Z=navigator.clipboard)!=null&&Z.writeText)||navigator.clipboard.writeText(A.helper).then(()=>n.ue.success("Copied to clipboard")).catch(()=>n.ue.error("Failed to copy"))},className:"cursor-pointer rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground transition-colors hover:bg-muted-foreground/20",children:A.helper})," ","to this query."," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/filters",target:"_blank",rel:"noreferrer",className:"underline-offset-2 hover:text-foreground hover:underline",children:"Learn more ↗"})]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:V||z,onClick:()=>{ct.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:le.current,exact:!0}),F(!0)},0)},className:"shrink-0",size:"xs",children:[V||z?e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(n.Play,{className:"h-3.5 w-3.5"}),"Run"]}),e.jsx(Me.EditorClearButton,{}),e.jsxs(n.Toggle,{pressed:a,onPressedChange:Z=>r(Z),title:a?"Remove Python post-processor":"Add a Python step to post-process the SQL result",className:"h-7 gap-1.5 rounded-control px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx("span",{className:"inline-flex h-3 w-3 items-center justify-center rounded-[2px] bg-muted font-mono text-[8px] font-bold text-muted-foreground",children:"Py"}),"Python",a?e.jsx(t.Check,{className:"h-3 w-3",strokeWidth:1.75}):e.jsx(n.Plus,{className:"h-3 w-3 text-muted-foreground",strokeWidth:1.75})]}),e.jsx(ur,{currentSql:u==null?void 0:u.sql,currentPython:u==null?void 0:u.python,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,onApplySql:me,onOpenFullAssistant:()=>D(!0)})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"flex shrink-0 flex-col gap-1.5 px-4 pb-3 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(n.EditableText,{value:u.title,onSave:Z=>L({...u,title:Z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:u})]}),e.jsx(n.EditableText,{value:(u.description||"").trim(),onSave:Z=>L({...u,description:Z.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})]}),e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:ue()}),Ne()]})}function xr(s,a){var c;let r=0,l=0;const u=Math.min(s.length,50);for(let o=0;o<u;o++){const d=(c=s[o])==null?void 0:c[a];if(!(d==null||d==="")){if(l++,typeof d=="number"||typeof d=="bigint")r++;else if(typeof d=="boolean")return"boolean"}}return l===0?"null":r/l>.7?"number":"text"}function hr(s){if(s===null)return"null";if(s===void 0)return"";if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);if(typeof s=="string")return s;try{return JSON.stringify(s)}catch{return String(s)}}function pr({data:s,card:a,paginationMetadata:r,onPaginationChange:l,onPageSizePreferenceChange:u,onSortChange:c,isLoading:o}){var N,M,j,O,D,L;const d=C.useMemo(()=>Object.keys(s[0]??{}),[s]),i=a.sql&&!((M=(N=a.preferences)==null?void 0:N.tablePrefs)!=null&&M.enableDevModePagination)?(O=(j=a.preferences)==null?void 0:j.tablePrefs)==null?void 0:O.pageSize:void 0,x=C.useMemo(()=>{var R;return n.sortByColumnsToSortState((R=a.config)==null?void 0:R.sortByColumns)},[(D=a.config)==null?void 0:D.sortByColumns]),{canSort:h,canUseLocalSorting:v,handlePaginationChange:f,handleSortChange:m,pagination:g,paginationMode:y,sorting:b}=n.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:l,onSortChange:c,pageSize:i,paginationMetadata:r,sortState:x}),w=C.useMemo(()=>b.filter(R=>d.includes(R.id)),[b,d]),A=C.useMemo(()=>{const R={};for(const p of d)R[p]=xr(s,p);return R},[d,s]),B=C.useMemo(()=>d.map(R=>{const F=A[R]==="number";return{accessorKey:R,enableSorting:h,header:({column:k})=>{const P=k.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",k.getCanSort()&&"cursor-pointer hover:text-foreground",F&&"justify-end"),onClick:()=>k.getCanSort()&&k.toggleSorting(k.getIsSorted()==="asc"),children:[e.jsx("span",{children:R}),P==="asc"?e.jsx(n.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):P==="desc"?e.jsx(n.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):k.getCanSort()?e.jsx(n.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:k})=>{const P=k(),V=P===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",F&&"text-right tabular-nums",V&&"text-muted-foreground/50 italic"),children:hr(P)})}}}),[h,A,d]),S=Math.max(B.length,1),E=n.useReactTable({data:s,columns:B,getCoreRowModel:n.getCoreRowModel(),getPaginationRowModel:y==="client"?n.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:v?n.getSortedRowModel():void 0,onPaginationChange:y==="disabled"?void 0:f,manualPagination:y==="server"||y==="disabled",manualSorting:!v,pageCount:y==="server"&&r?r.pageCount:void 0,state:{sorting:w,pagination:g}}),I=y==="server"&&r?r.totalCount:s.length,T=y!=="disabled"&&(y==="server"||I>10);return e.jsxs("div",{className:"relative flex h-full w-full min-h-0 flex-col",children:[o&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),e.jsxs(n.CustomScrollArea,{className:"min-h-0 grow overflow-auto text-foreground",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(n.TableHeader,{className:"sticky top-0 z-10",children:E.getHeaderGroups().map(R=>e.jsx(n.TableRow,{className:"border-b-0 hover:bg-transparent",children:R.headers.map(p=>{const k=A[p.id]==="number";return e.jsx(n.TableHead,{className:t.cn("group/header h-9 border-b bg-muted px-3 font-mono text-xs font-medium text-foreground",k&&"text-right"),children:p.isPlaceholder?null:n.flexRender(p.column.columnDef.header,p.getContext())},p.id)})},R.id))}),e.jsx(n.TableBody,{className:"font-mono",children:(L=E.getRowModel().rows)!=null&&L.length?E.getRowModel().rows.map((R,p)=>e.jsx(n.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",p%2===1&&"bg-muted/20"),"data-state":R.getIsSelected()&&"selected",children:R.getVisibleCells().map(F=>{const P=A[F.column.id]==="number";return e.jsx(n.TableCell,{className:t.cn("px-3 py-1.5 text-xs",P&&"text-right"),children:n.flexRender(F.column.columnDef.cell,F.getContext())},F.id)})},R.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:S,className:"h-24 text-center font-sans text-sm text-muted-foreground",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]}),e.jsx("div",{className:"shrink-0 border-t border-border/60 bg-muted/30 px-3 py-1.5 font-mono text-xs [&_*]:!text-xs",children:T?e.jsx(n.DataTablePagination,{totalColumns:d.length,pageCount:y==="server"&&r?r.pageCount:E.getPageCount(),pageIndex:E.getState().pagination.pageIndex,pageSize:E.getState().pagination.pageSize,rowCount:I,selectedRowCount:0,setPageIndex:E.setPageIndex,setPageSize:E.setPageSize,canPreviousPage:y==="server"&&r?r.hasPrevPage:E.getCanPreviousPage(),canNextPage:y==="server"&&r?r.hasNextPage:E.getCanNextPage(),previousPage:E.previousPage,nextPage:E.nextPage,onPageSizePreferenceChange:u,onClearSelection:()=>{},paginationMode:y,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[I.toLocaleString()," ",I===1?"row":"rows"," · ",d.length," ",d.length===1?"column":"columns"]}),w.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:w[0].id})," ",w[0].desc?"↓":"↑"]})]})})]})}const xn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function fr({className:s}){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.frame),l=t.useEditorStore(m=>m.editorContext),u=Me.useEffectiveEditorCardType(),{setCard:c,updateCardInFrame:o}=t.useEditorActions(),d=(l==null?void 0:l.type)==="documentSection"?xn.filter(m=>["table","pivotTable"].includes(m.value)):xn,i=["table","aggregateTable","pivotTable","detailTable"].includes(u),x=t.hasValidCardConfig(a.config),h=n.isCustomVisualConfigCard(a,r.cards);if(!i||!x||h)return e.jsx("div",{"aria-hidden":"true",className:t.cn("invisible flex items-center gap-5",s),children:e.jsx("span",{className:"-mb-px flex h-9 items-center border-b-2 border-transparent text-[12px]",children:"Placeholder"})});const v=m=>{if(m===u||h)return;const g=m,y=a.config??{},b=f(u,g,y),w={...a,type:g,config:b};c(w),o(w)},f=(m,g,y)=>{var w;if(m===g)return y;if(g==="detailTable"){const A=I=>I==null?void 0:I.toLowerCase().replace(/\s+/g,"").trim(),B=(I,T)=>{const N=[A(I.label),A(I.qualifiedFieldName),A(I.name)].filter(Boolean),M=[A(T.label),A(T.qualifiedFieldName),A(T.name)].filter(Boolean);return N.some(j=>M.includes(j))},S=(y.groupByColumns||[]).map(I=>({...I,role:"detail"})),E=((w=y.sortByColumns)==null?void 0:w.filter(I=>S.some(T=>B(I,T))))??[];return{...y,detailTableBackup:{groupByColumns:y.groupByColumns,metricColumns:y.metricColumns,pivotByColumns:y.pivotByColumns,sortByColumns:y.sortByColumns,rowAggregates:y.rowAggregates,columnAggregates:y.columnAggregates,comparisonType:y.comparisonType},detailColumns:S,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:E,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=y;if(m==="detailTable")if(y.detailTableBackup)b={...y,...y.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const A=(y.detailColumns||[]).map(B=>({...B,role:"groupby"}));b={...y,groupByColumns:A,detailColumns:[]}}return g==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:d.map(m=>{const g=u===m.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":g,onClick:()=>v(m.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",g?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:m.label},m.value)})})}const hn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function ps({error:s,errorSql:a,errorTitle:r="Unable to load data",onOpenInEditor:l,onDebugWithAssistant:u,onSendFeedback:c,showFeedbackButton:o=!0,className:d}){const[i,x]=C.useState(!1),f=!!u||!!(l&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TriangleAlert,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-500"}),e.jsx("span",{className:"text-[13px] font-medium text-foreground",children:r})]}),e.jsxs("div",{className:"relative rounded-[5px] border border-border/60 bg-background",children:[e.jsx(n.CopyButton,{text:s,className:"absolute right-1.5 top-1.5 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-60 overflow-auto px-2.5 py-2 pr-9",children:e.jsx("p",{className:"whitespace-pre-wrap break-all font-mono text-[12px] leading-[1.55] text-muted-foreground",children:s})})]}),f&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[u&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:u,children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),l&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:l,children:[e.jsx(Ln,{className:"h-3.5 w-3.5"}),"Open in editor"]})]}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[a&&e.jsx("button",{type:"button",onClick:()=>x(m=>!m),className:hn,children:i?"Hide query details":"Show query details"}),o&&c&&e.jsx("button",{type:"button",onClick:c,className:hn,children:"Report this issue"})]}),a&&e.jsx(n.Collapsible,{open:i,onOpenChange:x,children:e.jsxs(n.CollapsibleContent,{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Query"}),e.jsx(n.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-[5px] border border-border/60 bg-background p-2",children:e.jsx(n.CodeHighlighter,{code:a,language:"sql"})})]})})]})}function Bn(s,a){const r=t.useEditorStore(x=>x.card),l=t.useEditorStore(x=>x.isDevMode),{switchEditorMode:u,setRunSql:c,runAssistant:o}=t.useEditorActions();return{isDevMode:l,handleOpenInEditor:l?void 0:()=>{const x=a||r.sql||r.python||"";u("dev",{sqlToLoad:x}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:l?()=>{const x=`Can you help me debug this query?
171
+ `)}function lr(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const ns={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function or(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 cn(s){let a=0;for(let r=0;r<s.length;r+=1)a=(a<<5)-a+s.charCodeAt(r),a|=0;return String(a)}function dn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function ir(s,a){return s===n.SELF_HEAL_TIMELINE_STEP&&a>0?`${n.SELF_HEAL_TIMELINE_STEP} ${a}/${n.MAX_SELF_HEAL_ATTEMPTS}`:s}function Bt(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function un(s){var a;for(let r=s.length-1;r>=0;r-=1){const l=s[r];if(l.role!=="user")continue;const u=(a=l.metadata)==null?void 0:a.inlineRunToken;if(typeof u=="string"&&u.length>0)return u}}function cr(s){if(!s)return"";const a=s.trim(),r=s.match(/```sql\s*([\s\S]*?)```/i);if(r!=null&&r[1])return r[1].trim();const l=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return l!=null&&l[1]?l[1].trim():/^(select|with|insert|update|delete)\b/i.test(a)?a:""}function mn(s){for(let a=s.length-1;a>=0;a-=1){const r=s[a];if(!(r.role!=="assistant"||!Array.isArray(r.parts)))for(let l=r.parts.length-1;l>=0;l-=1){const u=r.parts[l];if((u==null?void 0:u.type)!=="text"||typeof(u==null?void 0:u.text)!="string")continue;const c=cr(u.text);if(c)return c}}return""}function dr({currentSql:s,currentPython:a,selectedDatabaseName:r,selectedSchemaName:l,selectedTableName:u,onApplySql:c,onOpenFullAssistant:o}){var Rt,St;const{authToken:d,tokenProps:i}=n.useSemaphorContext(),x=(Rt=n.useDashboardQuery().data)==null?void 0:Rt.assistantProfileId,h=t.useEditorStore(G=>G.isDevMode),v=t.useEditorStore(G=>G.selectedConnectionId),f=t.useEditorStore(G=>{var X;return(X=G.card.dataSource)==null?void 0:X.selectedEntities}),m=t.useAIInteractionStore(G=>G.currentAIContext.selectedEntities),g=m.length,{setCurrentAIContext:y}=t.useAIActions(),[b,w]=C.useState(""),[A,B]=C.useState(""),[S,E]=C.useState(""),[I,T]=C.useState("draft"),[N,M]=C.useState("draft"),[j,O]=C.useState(""),[D,L]=C.useState(!1),[R,p]=C.useState({status:"idle"}),[F,k]=C.useState(ns),[P,V]=C.useState(!1),[z,_]=C.useState(()=>Bt("inline-query-session")),q=C.useRef(null),W=C.useRef(null),$=C.useRef(null),U=C.useRef(0),se=C.useRef(0),ie=C.useRef(Bt("inline-run-token")),le=C.useRef(z),de=C.useRef(new Set),me=C.useRef(new Map),ue=C.useRef(0),Ne=C.useRef(""),we=C.useRef(!1),Te=C.useRef(!1),Z=C.useRef(ns),je=C.useRef(!1),Ie=C.useRef(null),ne=C.useRef(()=>{}),Ae=(St=i.apiServiceUrl)==null?void 0:St.replace(/\/$/,""),Le=Ae?`${Ae}/v1/sql/validate`:"/v1/sql/validate",ae=C.useCallback(G=>{k(X=>{const J=G(X);return Z.current=J,J})},[]),ve=C.useCallback((G,X)=>{ae(J=>J.runId===G?X(J):J)},[ae]),ye=C.useCallback(G=>se.current===G&&!de.current.has(G),[]),K=C.useCallback((G,X,J)=>{ve(G,ce=>{const ge=ce.timelineSteps.includes(X)?ce.timelineSteps:[...ce.timelineSteps,X];return{...ce,phase:(J==null?void 0:J.phase)||ce.phase,attempt:typeof(J==null?void 0:J.attempt)=="number"?J.attempt:ce.attempt,activeStep:X,timelineSteps:ge,finalOutcome:(J==null?void 0:J.finalOutcome)||ce.finalOutcome,hasTools:J!=null&&J.hasTools?!0:ce.hasTools}})},[ve]),Q=C.useCallback(()=>{const G=se.current+1,X=Bt("inline-run-token"),J=Bt("inline-query-session");return se.current=G,ie.current=X,le.current=J,_(J),de.current=new Set,me.current=new Map,ue.current=0,Ne.current="",je.current=!1,ae(()=>({runId:G,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:G,runToken:X,chatSessionId:J}},[ae]),te=C.useCallback(()=>{if(we.current||Te.current||g>0)return;const G=f||[];if(G.length===0)return;const X=t.useAIInteractionStore.getState().currentAIContext;y({...X,selectedEntities:G}),Te.current=!0},[g,f,y]),xe=C.useCallback(()=>{we.current=!0},[]),pe=C.useCallback((G,X,J)=>{lr(G,{runId:X,attemptCount:typeof(J==null?void 0:J.attemptCount)=="number"?J.attemptCount:ue.current,errorCode:J==null?void 0:J.errorCode,hasTools:typeof(J==null?void 0:J.hasTools)=="boolean"?J.hasTools:F.hasTools,entityCount:g,finalOutcome:(J==null?void 0:J.finalOutcome)||F.finalOutcome})},[g,F.finalOutcome,F.hasTools]),Fe=C.useCallback((G,X)=>{const J=$.current;if(!J)return;const ce={inlineRunToken:X};J({role:"user",parts:[{type:"text",text:G}],metadata:ce},{metadata:ce})},[]);C.useEffect(()=>{const G=Ie.current;!G||G.sessionId!==z||(Ie.current=null,Fe(G.message,G.runToken))},[z,Fe]);const ee=z,Se=C.useCallback(async({toolCall:G})=>{var Ve,Xe,lt,nt,_e,gt;if(ee!==le.current)return;const X=String(G.toolName||"").trim();if(!X)return;const J=se.current;if(!ye(J)){(Ve=W.current)==null||Ve.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(X==="getUserSql"){K(J,dn(X),{hasTools:!0}),pe("inline_tool_step",J,{hasTools:!0}),(Xe=W.current)==null||Xe.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const ce=n.INLINE_BLOCKED_MUTATING_TOOLS.has(X),ge=n.INLINE_ALLOWED_READ_ONLY_TOOLS.has(X);if(ce||!ge){(lt=W.current)==null||lt.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const be=dn(X);K(J,be,{phase:F.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),pe("inline_tool_step",J,{hasTools:!0});const Pe=((nt=G.input)==null?void 0:nt.sql)??((_e=G.args)==null?void 0:_e.sql);typeof Pe=="string"&&Pe.trim().length>0&&(je.current=!1,E(Pe.trim())),(gt=W.current)==null||gt.call(W,{tool:X,toolCallId:G.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,pe,F.phase,ye,ee,K]),fe=C.useCallback(({message:G,messages:X})=>{if(ee!==le.current)return;const J=un(X);if(!J||J!==ie.current)return;const ce=se.current;if(!ye(ce))return;const ge=mn([G])||mn(X);if(ge){je.current=!1,E(ge.trim());return}je.current&&Z.current.phase==="self-healing"&&ne.current(ce)},[ye,ee]),De=C.useCallback(G=>{if(ee!==le.current)return;const X=se.current;ye(X)&&je.current&&Z.current.phase==="self-healing"&&ne.current(X)},[ye,ee]),{setMessages:Oe,sendMessage:Qe,addToolResult:Ke,status:Ge,stop:re,error:ke,clearError:ze}=n.useChat({id:z,transport:new n.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const G=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:h,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:X,requestMetadata:J})=>{const ce=J==null?void 0:J.inlineRunToken,ge=un(G);return{body:{...X,inlineRunToken:ce||ge,messages:t.cleanupIncompleteMessages(G)}}}}),onToolCall:Se,onFinish:fe,onError:De,sendAutomaticallyWhen:n.lastAssistantMessageIsCompleteWithToolCalls});W.current=Ke,$.current=Qe;const Ce=!["ready","error"].includes(Ge),We=(ke==null?void 0:ke.message)||"Unable to generate a SQL draft right now. Try again.",Ee=C.useCallback(G=>{const X=se.current,J=Z.current.phase;if(!(J==="drafting"||J==="self-healing"||J==="validating")){G==="stopped"&&Ce&&re();return}de.current.add(X),je.current=!1,U.current+=1,Ne.current="",p({status:"idle"}),E(""),ze(),Oe([]),ve(X,ge=>({...ge,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),pe("inline_self_heal_stopped",X,{finalOutcome:"cancelled"}),(Ce||G==="stopped")&&re()},[ze,pe,Ce,Oe,re,ve]),yt=C.useCallback(async(G,X)=>{var ce;if(!ye(X))return null;const J=U.current+1;U.current=J,K(X,"Validating SQL",{phase:"validating"}),p({status:"validating"});try{const ge=await t.postRequestRegular(Le,(d==null?void 0:d.accessToken)||"",{sql:G,connectionId:v||void 0});if(U.current!==J||!ye(X))return null;if((ge==null?void 0:ge.valid)===!0)return p({status:"valid",message:"SQL validation passed."}),ve(X,Ve=>({...Ve,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),pe("inline_draft_validated",X,{finalOutcome:"validated"}),{status:"valid"};const be=or(ge==null?void 0:ge.errorCode)||"UNKNOWN",Pe=typeof(ge==null?void 0:ge.error)=="string"&&ge.error||typeof((ce=ge==null?void 0:ge.details)==null?void 0:ce.error)=="string"&&ge.details.error||"SQL validation failed. Please revise the query draft.";return p({status:"invalid",message:Pe,errorCode:be}),ve(X,Ve=>({...Ve,lastValidation:{valid:!1,error:Pe,errorCode:be}})),pe("inline_validation_failed",X,{errorCode:be,finalOutcome:"validation_failed"}),{status:"invalid",error:Pe,errorCode:be}}catch(ge){if(U.current!==J||!ye(X))return null;const be=t.getRequestErrorMessage(ge,"Validation service unavailable. You can still replace and run.");return p({status:"error",message:be,errorCode:"SQL_CONNECTION_ERROR"}),ve(X,Pe=>({...Pe,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:be,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:be,errorCode:"SQL_CONNECTION_ERROR"}}},[d==null?void 0:d.accessToken,pe,ye,v,Le,ve,K]),Ze=C.useCallback((G,X,J,ce)=>{let ge=J,be="validation_failed",Pe="Validating SQL";X==="attempt_limit"?(ge=`Couldn't auto-fix after ${n.MAX_SELF_HEAL_ATTEMPTS} attempts. ${J}`,be="self_heal_exhausted",Pe=`Auto-fix stopped (${n.MAX_SELF_HEAL_ATTEMPTS} attempts)`):X==="duplicate"&&(ge=`Auto-fix stopped (repeated validation failure). ${J}`,be="self_heal_duplicate_stopped",Pe="Auto-fix stopped (repeated failure)"),p({status:"invalid",message:ge,errorCode:ce}),K(G,Pe,{phase:"error",finalOutcome:be}),ve(G,Ve=>({...Ve,phase:"error",finalOutcome:be,lastValidation:{valid:!1,error:ge,errorCode:ce}})),X!=="terminal"&&pe("inline_self_heal_stopped",G,{errorCode:ce,finalOutcome:be}),je.current=!1},[pe,ve,K]),kt=C.useCallback(G=>{const X="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",J="self_heal_no_draft";p({status:"invalid",message:X,errorCode:"UNKNOWN"}),K(G,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:J}),ve(G,ce=>({...ce,phase:"error",finalOutcome:J,lastValidation:{valid:!1,error:X,errorCode:"UNKNOWN"}})),pe("inline_self_heal_stopped",G,{errorCode:"UNKNOWN",finalOutcome:J}),je.current=!1},[pe,ve,K]);ne.current=kt,C.useEffect(()=>{const G=S.trim(),X=se.current;if(!G){if(U.current+=1,Ne.current="",Z.current.phase==="error")return;p({status:"idle"});return}if(!ye(X)||Ce)return;const J=`${X}:${ue.current}:${cn(G)}`;if(Ne.current===J)return;Ne.current=J;let ce=!1;return(async()=>{const be=await yt(G,X);if(!be||ce||!ye(X)||be.status!=="invalid")return;if(!n.RECOVERABLE_SQL_ERROR_CODES.has(be.errorCode)){Ze(X,"terminal",be.error,be.errorCode);return}const Pe=`${cn(G)}::${be.errorCode}`,Ve=(me.current.get(Pe)||0)+1;if(me.current.set(Pe,Ve),Ve>=2){Ze(X,"duplicate",be.error,be.errorCode);return}if(ue.current>=n.MAX_SELF_HEAL_ATTEMPTS){Ze(X,"attempt_limit",be.error,be.errorCode);return}const Xe=ue.current+1;ue.current=Xe,K(X,n.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:Xe}),pe("inline_self_heal_attempt",X,{attemptCount:Xe,errorCode:be.errorCode}),je.current=!0,ze(),Oe([]),E("");const lt=m.map(_e=>{const gt=_e!=null&&_e.database?`${_e.database}.`:"",Xt=_e!=null&&_e.schema?`${_e.schema}.`:"",Zt=(_e==null?void 0:_e.name)||"unknown";return`${gt}${Xt}${Zt}`}),nt=rr({request:A,failedSql:G,errorMessage:be.error,errorCode:be.errorCode,selectedDatabaseName:r||"",selectedSchemaName:l||"",selectedTableName:u||"",contextEntityLabels:lt});Fe(nt,ie.current)})(),()=>{ce=!0}},[ze,m,pe,Ce,ye,A,S,r,l,u,Fe,Oe,Ze,K,yt]);const Je=(s==null?void 0:s.trim())||"",Dt=C.useCallback((G="draft")=>{if(Ce)return;const X=b.trim();if(!X)return;const J=G==="refine"&&Je?"refine":"draft",ce=J==="refine"?Je:"",ge=Je,{runId:be,runToken:Pe,chatSessionId:Ve}=Q();pe("inline_draft_started",be,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),te(),ze(),B(X),E(""),T(J),O(ce),L(!1),p({status:"idle"}),U.current+=1,Oe([]),V(!0);const Xe=ar({request:X,mode:J,currentSql:ge,selectedTableName:u||"",selectedSchemaName:l||"",selectedDatabaseName:r||""});Ie.current={sessionId:Ve,message:Xe,runToken:Pe}},[Q,ze,Je,pe,Ce,b,te,r,l,u,Oe]),dt=C.useCallback(G=>{const X=S.trim();X&&(c(X,G),G||V(!1))},[c,S]),et=S.trim().length>0,At=["valid","invalid","error"].includes(R.status),Nt=et&&At,Ht=R.status==="invalid",Mt=R.status==="validating",ut=et&&A.length>0&&A===b.trim(),mt=Je.length>0,xt=b.length>0,ht=ut&&I==="draft",Ue=ut&&I==="refine"&&j===Je,tt=N==="refine"&&!mt?"draft":N,st=(tt==="refine"?Ue:ht)?"Open composer preview":"Generate composer SQL",Lt=b.trim().length>0||A.trim().length>0||et||R.status!=="idle"||F.timelineSteps.length>0,Ct=C.useCallback((G="draft")=>{if(Ce)return;if((G==="refine"?Ue:ht)&&!P){te(),V(!0);return}Dt(G)},[ht,Ue,Dt,Ce,P,te]),pt=C.useCallback(()=>{te(),V(!0)},[te]),Wt=C.useCallback(G=>{Ee("cancelled"),w(G)},[Ee]),Jt=C.useCallback(()=>{Ce||(Ee("cancelled"),je.current=!1,U.current+=1,Ne.current="",ue.current=0,w(""),B(""),E(""),T("draft"),M("draft"),O(""),L(!1),p({status:"idle"}),ze(),Oe([]),ae(G=>({...ns,runId:G.runId})))},[Ee,ze,Ce,Oe,ae]),Yt=C.useCallback(G=>{G||Ee("cancelled"),V(G)},[Ee]),He=F.timelineSteps.findIndex(G=>G===F.activeStep),Ft=F.phase==="self-healing"?"Fixing validation issue":F.phase==="validating"?"Validating SQL":F.activeStep||"Drafting SQL",ft=R.status==="valid"?{label:"Validation passed",className:"border-emerald-500/30 bg-emerald-500/10 text-emerald-700",detail:R.message}:R.status==="invalid"?{label:"Validation failed",className:"border-destructive/40 bg-destructive/10 text-destructive",detail:R.message}:R.status==="error"?{label:"Validation unavailable",className:"border-border/60 bg-muted/20 text-muted-foreground",detail:R.message}:null;return e.jsxs("div",{ref:q,className:"relative flex h-7 min-w-[320px] flex-1 items-center",children:[e.jsx(n.Sparkles,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground",strokeWidth:1.75}),e.jsx(t.Input,{value:b,onChange:G=>Wt(G.target.value),onFocus:pt,onClick:pt,onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),Ct(tt))},placeholder:"Ask in plain English — e.g. top 10 customers by profit last quarter",className:["h-7 rounded-[5px] border border-border/60 bg-background pl-7 text-[12px] shadow-none placeholder:text-muted-foreground/70 focus-visible:border-ring focus-visible:ring-0",xt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:P,onOpenChange:Yt,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:[xt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),Ee("cancelled"),w("")},disabled:Ce,"aria-label":"Clear input",title:"Clear input",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:G=>{G.preventDefault(),Ct(tt)},disabled:Ce,"aria-label":st,title:st,children:e.jsx(La,{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:G=>{G.preventDefault()},onInteractOutside:G=>{var J;const X=G.target;X&&((J=q.current)!=null&&J.contains(X))&&G.preventDefault()},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"inline-flex h-7 items-center rounded-[5px] border border-border/60 bg-background p-0.5",children:[e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",tt==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{M("draft"),L(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",tt==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>M("refine"),disabled:!mt,children:"Refine"})]}),e.jsx(n.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:xe})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{Ee("stopped")},children:"Stop"}),!Ce&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Jt,disabled:!Lt,children:"Clear"})]})]}),F.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[F.timelineSteps.map((G,X)=>{const J=G===F.activeStep&&["drafting","validating","self-healing"].includes(F.phase),ce=!J&&He>=0&&X<He;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",J?"border-foreground/30 bg-foreground/10 text-foreground":ce?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:ir(G,F.attempt)},`${G}-${X}`)}),ft&&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]",ft.className].join(" "),children:ft.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:ft.detail})]})})]}),(Ce||F.phase==="self-healing"||R.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"}),Ft]}),ke&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:We}),I==="refine"&&j&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-[5px] border border-border/60 bg-muted/20 px-2.5 py-1.5 text-[11px]",children:[e.jsx("span",{className:"text-muted-foreground",children:"Refining editor SQL"}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"xs",onClick:()=>L(G=>!G),children:D?"Hide base SQL":"View base SQL"})]}),D&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:j,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Base SQL"})})]}),Nt?e.jsxs("div",{className:"space-y-1",children:[I==="refine"&&e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Refined SQL"}),e.jsx("div",{className:"max-h-[200px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:S,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Drafted SQL"})})]}):et?e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:"Validating SQL draft before preview."}):!Ce&&e.jsx("div",{className:"rounded-[5px] border border-dashed border-border/70 px-3 py-2 text-[11px] text-muted-foreground",children:mt?"Choose Draft New or Refine Current, then press Enter or click send.":"Describe what you want to query, then press Enter or click send to generate a SQL preview."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:o,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:Ce||!Nt,onClick:()=>dt(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:Ce||!Nt||Mt||Ht,onClick:()=>dt(!0),children:"Replace & Run"})]})]})})]})]})}function ur(){var we,Te;const s=n.useQueryClient(),[a,r]=C.useState(!1),l=t.useEditorStore(Z=>Z.frame),u=t.useEditorStore(Z=>Z.card);t.useEditorStore(Z=>Z.isShowingVisual),t.useEditorStore(Z=>Z.selectedConnectionId),t.useEditorStore(Z=>Z.tempQueryData);const c=t.useEditorStore(Z=>Z.selectedDatabaseName);t.useEditorStore(Z=>Z.selectedDatamodelId);const o=t.useEditorStore(Z=>Z.selectedSchemaName);t.useEditorStore(Z=>Z.showAIDialog);const d=t.useEditorStore(Z=>Z.selectedTableName),i=t.useDashboardStore(Z=>{var je,Ie;return((Ie=(je=Z.dashboard)==null?void 0:je.filters)==null?void 0:Ie.length)??0}),x=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(u==null?void 0:u.id)??""]),h=C.useMemo(()=>n.findCustomVisualConfigCard(l,u),[l,u]),{manifest:v}=n.useCustomVisual(((we=h==null?void 0:h.customCardPreferences)==null?void 0:we.url)||""),f=C.useMemo(()=>{var Z;return(Z=v==null?void 0:v.visuals)==null?void 0:Z.find(je=>{var Ie;return je.name===((Ie=h==null?void 0:h.customCardPreferences)==null?void 0:Ie.componentName)})},[v,(Te=h==null?void 0:h.customCardPreferences)==null?void 0:Te.componentName]),m=n.resolveMultiInputType(h,f),g=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:h,isMultiInputVisual:m==="multiple"}),[l,h,m]),y=C.useMemo(()=>{const Z=g.findIndex(je=>(je==null?void 0:je.id)===(u==null?void 0:u.id));return Z<0?-1:n.getSlotIndexForCard(u,Z)},[g,u]),b=C.useMemo(()=>!h||m!=="multiple"||y<0?u.type:n.getEffectiveCardTypeForSlot(u,y,f==null?void 0:f.slots)??u.type,[h,m,y,u,f==null?void 0:f.slots]),w=C.useMemo(()=>b!==u.type?{...u,type:b}:u,[u,b]),A=C.useMemo(()=>i===0?null:nr(u==null?void 0:u.sql),[u==null?void 0:u.sql,i]),B=C.useRef(!0),{setCardCustomCfg:S,setQueryResultColumns:E,setCardSql:I,setTempQueryData:T,setPythonStdOut:N,setCardPreferences:M,setCardType:j,setCardPython:O,setShowAIDialog:D,setCard:L,updateCardInFrame:R}=t.useEditorActions();t.useEditorStore(Z=>Z.onSave),t.useEditorStore(Z=>Z.onClose),t.useEditorStore(Z=>Z.actions.setSqlGen);const p=t.useEditorStore(Z=>Z.runSql),F=t.useEditorStore(Z=>Z.actions.setRunSql),k=t.useEditorStore(Z=>Z.actions.setIsSqlRunning),{data:P,isLoading:V,isFetching:z,isSuccess:_,isError:q,error:W,errorSql:$,queryKey:U,refetch:se,errorMessage:ie}=n.useEditorCardQuery(w),le=C.useRef(U);le.current=U,C.useEffect(()=>{if(P&&(P.rowLimitExceeded&&n.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),N((P==null?void 0:P.output)||""),P.records.length>0)){const{dimensionKeys:Z}=n.getKeys(P.records);E(Z)}},[P,E,N]),C.useEffect(()=>{(V||z)&&k(!0),(q||_)&&k(!1),q&&(E([]),N(""))},[V,z,P,N,q,_,k,E,W]),C.useEffect(()=>{p&&(s.getQueryData(U)||se(),F(!1))},[p,se,F,U,s]);const de=C.useRef(se);de.current=se,C.useEffect(()=>{if(B.current){B.current=!1;return}de.current()},[x]);function me(Z,je){I(Z),je&&F(!0)}function ue(){return e.jsxs(n.ResizablePanelGroup,{className:"flex grow gap-2 px-4",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(n.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-full overflow-hidden rounded-control border border-border bg-background",children:e.jsx(Ja,{})}),a&&e.jsx("code",{className:"absolute right-3 top-2 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs(n.PanelResizeHandle,{className:"group/divider relative my-1 flex h-6 w-full shrink-0 cursor-row-resize items-center gap-3 px-1 outline-none",children:[e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(n.ArrowDown,{className:"h-3 w-3",strokeWidth:1.75}),"Post-process with Python"]}),e.jsx("span",{className:"h-px flex-1 bg-border transition-colors group-hover/divider:bg-foreground/30"}),e.jsx("button",{type:"button","aria-label":"Close Python editor",onClick:Z=>{Z.stopPropagation(),r(!1)},onPointerDown:Z=>Z.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3",strokeWidth:1.75})})]}),e.jsx(n.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:e.jsxs("div",{id:"python-container",className:"relative flex w-full flex-col overflow-hidden rounded-control border border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30 px-3 py-1.5 text-[11px] text-muted-foreground",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"rounded-control bg-background px-1.5 py-0.5 font-mono text-[10px] text-foreground/80",children:"Py"}),e.jsx("code",{className:"truncate font-mono text-[11px] text-foreground/80",children:"def process(df) → df"}),e.jsx("span",{className:"hidden truncate text-muted-foreground/80 sm:inline",children:"Runs after SQL · receives a DataFrame"})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Python 3.11"})]}),e.jsx("div",{className:"relative flex flex-1",children:e.jsx(Xa,{})})]})})]})]})}function Ne(){return e.jsxs("div",{role:"editor-controls",className:"flex w-full flex-wrap items-center gap-2 px-4 pb-2 pt-3",children:[A&&e.jsxs("div",{className:"mb-1.5 mr-6 flex w-full items-center gap-1.5 px-1 text-[11px] text-muted-foreground",children:[e.jsx(n.Filter,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:["Not subscribed to dashboard filters. Add"," ",e.jsx("button",{type:"button",title:"Click to copy",onClick:()=>{var Z;typeof navigator>"u"||!((Z=navigator.clipboard)!=null&&Z.writeText)||navigator.clipboard.writeText(A.helper).then(()=>n.ue.success("Copied to clipboard")).catch(()=>n.ue.error("Failed to copy"))},className:"cursor-pointer rounded-[4px] bg-muted px-1 py-0.5 font-mono text-[10px] text-foreground transition-colors hover:bg-muted-foreground/20",children:A.helper})," ","to this query."," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/filters",target:"_blank",rel:"noreferrer",className:"underline-offset-2 hover:text-foreground hover:underline",children:"Learn more ↗"})]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:V||z,onClick:()=>{ct.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:le.current,exact:!0}),F(!0)},0)},className:"shrink-0",size:"xs",children:[V||z?e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(n.Play,{className:"h-3.5 w-3.5"}),"Run"]}),e.jsx(Me.EditorClearButton,{}),e.jsxs(n.Toggle,{pressed:a,onPressedChange:Z=>r(Z),title:a?"Remove Python post-processor":"Add a Python step to post-process the SQL result",className:"h-7 gap-1.5 rounded-control px-2.5 text-[12px]",size:"sm",variant:"outline",children:[e.jsx("span",{className:"inline-flex h-3 w-3 items-center justify-center rounded-[2px] bg-muted font-mono text-[8px] font-bold text-muted-foreground",children:"Py"}),"Python",a?e.jsx(t.Check,{className:"h-3 w-3",strokeWidth:1.75}):e.jsx(n.Plus,{className:"h-3 w-3 text-muted-foreground",strokeWidth:1.75})]}),e.jsx(dr,{currentSql:u==null?void 0:u.sql,currentPython:u==null?void 0:u.python,selectedDatabaseName:c,selectedSchemaName:o,selectedTableName:d,onApplySql:me,onOpenFullAssistant:()=>D(!0)})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"flex shrink-0 flex-col gap-1.5 px-4 pb-3 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(n.EditableText,{value:u.title,onSave:Z=>L({...u,title:Z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:u})]}),e.jsx(n.EditableText,{value:(u.description||"").trim(),onSave:Z=>L({...u,description:Z.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})]}),e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:ue()}),Ne()]})}function mr(s,a){var c;let r=0,l=0;const u=Math.min(s.length,50);for(let o=0;o<u;o++){const d=(c=s[o])==null?void 0:c[a];if(!(d==null||d==="")){if(l++,typeof d=="number"||typeof d=="bigint")r++;else if(typeof d=="boolean")return"boolean"}}return l===0?"null":r/l>.7?"number":"text"}function xr(s){if(s===null)return"null";if(s===void 0)return"";if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);if(typeof s=="string")return s;try{return JSON.stringify(s)}catch{return String(s)}}function hr({data:s,card:a,paginationMetadata:r,onPaginationChange:l,onPageSizePreferenceChange:u,onSortChange:c,isLoading:o}){var N,M,j,O,D,L;const d=C.useMemo(()=>Object.keys(s[0]??{}),[s]),i=a.sql&&!((M=(N=a.preferences)==null?void 0:N.tablePrefs)!=null&&M.enableDevModePagination)?(O=(j=a.preferences)==null?void 0:j.tablePrefs)==null?void 0:O.pageSize:void 0,x=C.useMemo(()=>{var R;return n.sortByColumnsToSortState((R=a.config)==null?void 0:R.sortByColumns)},[(D=a.config)==null?void 0:D.sortByColumns]),{canSort:h,canUseLocalSorting:v,handlePaginationChange:f,handleSortChange:m,pagination:g,paginationMode:y,sorting:b}=n.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:l,onSortChange:c,pageSize:i,paginationMetadata:r,sortState:x}),w=C.useMemo(()=>b.filter(R=>d.includes(R.id)),[b,d]),A=C.useMemo(()=>{const R={};for(const p of d)R[p]=mr(s,p);return R},[d,s]),B=C.useMemo(()=>d.map(R=>{const F=A[R]==="number";return{accessorKey:R,enableSorting:h,header:({column:k})=>{const P=k.getIsSorted();return e.jsxs("div",{className:t.cn("flex select-none items-center gap-1.5 transition-colors",k.getCanSort()&&"cursor-pointer hover:text-foreground",F&&"justify-end"),onClick:()=>k.getCanSort()&&k.toggleSorting(k.getIsSorted()==="asc"),children:[e.jsx("span",{children:R}),P==="asc"?e.jsx(n.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):P==="desc"?e.jsx(n.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):k.getCanSort()?e.jsx(n.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:k})=>{const P=k(),V=P===null;return e.jsx("div",{className:t.cn("whitespace-pre-wrap break-all",F&&"text-right tabular-nums",V&&"text-muted-foreground/50 italic"),children:xr(P)})}}}),[h,A,d]),S=Math.max(B.length,1),E=n.useReactTable({data:s,columns:B,getCoreRowModel:n.getCoreRowModel(),getPaginationRowModel:y==="client"?n.getPaginationRowModel():void 0,onSortingChange:m,getSortedRowModel:v?n.getSortedRowModel():void 0,onPaginationChange:y==="disabled"?void 0:f,manualPagination:y==="server"||y==="disabled",manualSorting:!v,pageCount:y==="server"&&r?r.pageCount:void 0,state:{sorting:w,pagination:g}}),I=y==="server"&&r?r.totalCount:s.length,T=y!=="disabled"&&(y==="server"||I>10);return e.jsxs("div",{className:"relative flex h-full w-full min-h-0 flex-col",children:[o&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),e.jsxs(n.CustomScrollArea,{className:"min-h-0 grow overflow-auto text-foreground",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(n.TableHeader,{className:"sticky top-0 z-10",children:E.getHeaderGroups().map(R=>e.jsx(n.TableRow,{className:"border-b-0 hover:bg-transparent",children:R.headers.map(p=>{const k=A[p.id]==="number";return e.jsx(n.TableHead,{className:t.cn("group/header h-9 border-b bg-muted px-3 font-mono text-xs font-medium text-foreground",k&&"text-right"),children:p.isPlaceholder?null:n.flexRender(p.column.columnDef.header,p.getContext())},p.id)})},R.id))}),e.jsx(n.TableBody,{className:"font-mono",children:(L=E.getRowModel().rows)!=null&&L.length?E.getRowModel().rows.map((R,p)=>e.jsx(n.TableRow,{className:t.cn("h-[34px] border-b border-border/40 transition-colors",p%2===1&&"bg-muted/20"),"data-state":R.getIsSelected()&&"selected",children:R.getVisibleCells().map(F=>{const P=A[F.column.id]==="number";return e.jsx(n.TableCell,{className:t.cn("px-3 py-1.5 text-xs",P&&"text-right"),children:n.flexRender(F.column.columnDef.cell,F.getContext())},F.id)})},R.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:S,className:"h-24 text-center font-sans text-sm text-muted-foreground",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]}),e.jsx("div",{className:"shrink-0 border-t border-border/60 bg-muted/30 px-3 py-1.5 font-mono text-xs [&_*]:!text-xs",children:T?e.jsx(n.DataTablePagination,{totalColumns:d.length,pageCount:y==="server"&&r?r.pageCount:E.getPageCount(),pageIndex:E.getState().pagination.pageIndex,pageSize:E.getState().pagination.pageSize,rowCount:I,selectedRowCount:0,setPageIndex:E.setPageIndex,setPageSize:E.setPageSize,canPreviousPage:y==="server"&&r?r.hasPrevPage:E.getCanPreviousPage(),canNextPage:y==="server"&&r?r.hasNextPage:E.getCanNextPage(),previousPage:E.previousPage,nextPage:E.nextPage,onPageSizePreferenceChange:u,onClearSelection:()=>{},paginationMode:y,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[I.toLocaleString()," ",I===1?"row":"rows"," · ",d.length," ",d.length===1?"column":"columns"]}),w.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:w[0].id})," ",w[0].desc?"↓":"↑"]})]})})]})}const xn=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function pr({className:s}){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.frame),l=t.useEditorStore(m=>m.editorContext),u=Me.useEffectiveEditorCardType(),{setCard:c,updateCardInFrame:o}=t.useEditorActions(),d=(l==null?void 0:l.type)==="documentSection"?xn.filter(m=>["table","pivotTable"].includes(m.value)):xn,i=["table","aggregateTable","pivotTable","detailTable"].includes(u),x=t.hasValidCardConfig(a.config),h=n.isCustomVisualConfigCard(a,r.cards);if(!i||!x||h)return e.jsx("div",{"aria-hidden":"true",className:t.cn("invisible flex items-center gap-5",s),children:e.jsx("span",{className:"-mb-px flex h-9 items-center border-b-2 border-transparent text-[12px]",children:"Placeholder"})});const v=m=>{if(m===u||h)return;const g=m,y=a.config??{},b=f(u,g,y),w={...a,type:g,config:b};c(w),o(w)},f=(m,g,y)=>{var w;if(m===g)return y;if(g==="detailTable"){const A=I=>I==null?void 0:I.toLowerCase().replace(/\s+/g,"").trim(),B=(I,T)=>{const N=[A(I.label),A(I.qualifiedFieldName),A(I.name)].filter(Boolean),M=[A(T.label),A(T.qualifiedFieldName),A(T.name)].filter(Boolean);return N.some(j=>M.includes(j))},S=(y.groupByColumns||[]).map(I=>({...I,role:"detail"})),E=((w=y.sortByColumns)==null?void 0:w.filter(I=>S.some(T=>B(I,T))))??[];return{...y,detailTableBackup:{groupByColumns:y.groupByColumns,metricColumns:y.metricColumns,pivotByColumns:y.pivotByColumns,sortByColumns:y.sortByColumns,rowAggregates:y.rowAggregates,columnAggregates:y.columnAggregates,comparisonType:y.comparisonType},detailColumns:S,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:E,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=y;if(m==="detailTable")if(y.detailTableBackup)b={...y,...y.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const A=(y.detailColumns||[]).map(B=>({...B,role:"groupby"}));b={...y,groupByColumns:A,detailColumns:[]}}return g==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:d.map(m=>{const g=u===m.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":g,onClick:()=>v(m.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",g?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:m.label},m.value)})})}const hn="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function ps({error:s,errorSql:a,errorTitle:r="Unable to load data",onOpenInEditor:l,onDebugWithAssistant:u,onSendFeedback:c,showFeedbackButton:o=!0,className:d}){const[i,x]=C.useState(!1),f=!!u||!!(l&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TriangleAlert,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-500"}),e.jsx("span",{className:"text-[13px] font-medium text-foreground",children:r})]}),e.jsxs("div",{className:"relative rounded-[5px] border border-border/60 bg-background",children:[e.jsx(n.CopyButton,{text:s,className:"absolute right-1.5 top-1.5 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-60 overflow-auto px-2.5 py-2 pr-9",children:e.jsx("p",{className:"whitespace-pre-wrap break-all font-mono text-[12px] leading-[1.55] text-muted-foreground",children:s})})]}),f&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[u&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:u,children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),l&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:l,children:[e.jsx(Fn,{className:"h-3.5 w-3.5"}),"Open in editor"]})]}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[a&&e.jsx("button",{type:"button",onClick:()=>x(m=>!m),className:hn,children:i?"Hide query details":"Show query details"}),o&&c&&e.jsx("button",{type:"button",onClick:c,className:hn,children:"Report this issue"})]}),a&&e.jsx(n.Collapsible,{open:i,onOpenChange:x,children:e.jsxs(n.CollapsibleContent,{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Query"}),e.jsx(n.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-[5px] border border-border/60 bg-background p-2",children:e.jsx(n.CodeHighlighter,{code:a,language:"sql"})})]})})]})}function Vn(s,a){const r=t.useEditorStore(x=>x.card),l=t.useEditorStore(x=>x.isDevMode),{switchEditorMode:u,setRunSql:c,runAssistant:o}=t.useEditorActions();return{isDevMode:l,handleOpenInEditor:l?void 0:()=>{const x=a||r.sql||r.python||"";u("dev",{sqlToLoad:x}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:l?()=>{const x=`Can you help me debug this query?
172
172
 
173
173
  Error:
174
174
 
@@ -178,6 +178,6 @@ ${l}`].filter(Boolean).join(`
178
178
 
179
179
  ${a||r.sql||r.python}
180
180
 
181
- `;o(x)}:void 0}}function Vn({className:s,style:a,...r}){var Q,te,xe,pe,Fe;const l=t.useEditorStore(ee=>ee.card),u=n.useDashboardAppearance(),o=t.useEditorStore(ee=>ee.isDevMode)?!1:((Q=l.customCardPreferences)==null?void 0:Q.showCardHeader)??!0,d=((xe=(te=l.preferences)==null?void 0:te.displayOptions)==null?void 0:xe.showInlineFilterBar)??!0,i=t.useEditorStore(ee=>ee.frame),x=t.useEditorStore(ee=>ee.inlineFilterValuesMap[l.id]),h=t.useDashboardStore(ee=>ee.dashboard.filters),v=t.useDashboardStore(ee=>ee.selectedSheetId),[f,m]=C.useState(!1),{currentUser:g}=n.useCurrentUserInfo(),{tokenProps:y}=C.useContext(n.SemaphorContext),b=t.useEditorStore(ee=>ee.actions.setRunSql),w=t.useEditorStore(ee=>ee.actions.setCardInlineFilterValue),A=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),{updateFilter:B}=t.useDashboardActions(),S=h==null?void 0:h.find(ee=>ee.id===i.filterId),E=C.useMemo(()=>n.findCustomVisualConfigCard(i,l),[i,l]),{manifest:I}=n.useCustomVisual(((pe=E==null?void 0:E.customCardPreferences)==null?void 0:pe.url)||""),T=C.useMemo(()=>{var ee;return(ee=I==null?void 0:I.visuals)==null?void 0:ee.find(Se=>{var fe;return Se.name===((fe=E==null?void 0:E.customCardPreferences)==null?void 0:fe.componentName)})},[I,(Fe=E==null?void 0:E.customCardPreferences)==null?void 0:Fe.componentName]),N=n.resolveMultiInputType(E,T),M=C.useMemo(()=>n.getCustomVisualInputCards({frame:i,configCard:E,isMultiInputVisual:N==="multiple"}),[i,E,N]),j=C.useMemo(()=>{const ee=M.findIndex(Se=>(Se==null?void 0:Se.id)===(l==null?void 0:l.id));return ee<0?-1:n.getSlotIndexForCard(l,ee)},[M,l]),O=C.useMemo(()=>!E||N!=="multiple"||j<0?l.type:n.getEffectiveCardTypeForSlot(l,j,T==null?void 0:T.slots)??l.type,[E,N,j,l,T==null?void 0:T.slots]),D=O??l.type,L=C.useMemo(()=>D===l.type?l:{...l,type:D},[l,D]),R=C.useMemo(()=>O!==l.type?{...l,type:O}:l,[l,O]),{data:p,isLoading:F,isFetching:k,errorMessage:P,errorSql:V,pagination:z}=n.useEditorCardQuery(R),{handleOpenInEditor:_,handleDebugWithAssistant:q}=Bn(P,V||l.sql||l.python),W=C.useMemo(()=>(p==null?void 0:p.records)||[],[p==null?void 0:p.records]),{setCard:$,updateCardInFrame:U}=t.useEditorActions(),{data:se}=n.useTopoJson(L),ie=L.id,le=L.config,de=L.interactionConfig,me=L.customCfg,ue=L.preferences,Ne=L.queryConfig,we=!!L.sql,Te=p==null?void 0:p.records,Z=C.useMemo(()=>({id:ie,type:D,config:le,interactionConfig:de,sql:we?"__editor_sql__":""}),[ie,D,le,de,we]),je=C.useMemo(()=>{var ee;return D!=="pivotTable"||!((ee=p==null?void 0:p.records)!=null&&ee.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[D,p==null?void 0:p.records,p==null?void 0:p.columnSubtotalMeta,p==null?void 0:p.subtotalColumns,p==null?void 0:p.pivotSchema,p==null?void 0:p.groupByColumns]),Ie=n.usePivotTableConfig(L,je),ne=()=>{m(!0)},Ae=C.useMemo(()=>{const ee=typeof window<"u"?window.location.href:"",Se=typeof navigator<"u"?navigator.userAgent:"",fe=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:g,tokenContext:y,systemState:{cardConfig:l.config,dataSource:l.dataSource,dashboardFilters:h,errorMessage:P||void 0,errorSql:V||l.sql||l.python,generatedSql:V||l.sql},metadata:{url:ee,userAgent:Se,timestamp:new Date().toISOString(),viewport:fe}}},[g,y,l,h,P,V]),Le=(ee,Se)=>{var De,Oe;const fe={...l,paginationConfig:{page:ee+1,pageSize:Se}};$(fe),U(fe),l.sql&&((Oe=(De=l.preferences)==null?void 0:De.tablePrefs)!=null&&Oe.enableDevModePagination)&&b(!0)},ae=ee=>{var De,Oe,Qe,Ke,Ge;const Se=n.sortStateToSortByColumns(ee,(De=l.config)==null?void 0:De.metricColumns,(Oe=l.config)==null?void 0:Oe.groupByColumns,(Qe=l.config)==null?void 0:Qe.detailColumns),fe={...l,config:{...l.config||{},sortByColumns:Se}};$(fe),U(fe),l.sql&&((Ge=(Ke=l.preferences)==null?void 0:Ke.tablePrefs)!=null&&Ge.enableDevModePagination)&&b(!0)},ve=C.useMemo(()=>!ie||!Te?null:n.createChartConfig({card:Z,data:Te,cardType:D,queryConfig:Ne,customCfg:me,preferences:ue,topoJson:se}),[Z,ie,me,ue,Ne,Te,D,se]);function ye(ee){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:ee})})}function K(){var ee;if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!F&&!k)return P?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ps,{error:P,errorSql:V||l.sql||l.python,onOpenInEditor:_,onDebugWithAssistant:q,onSendFeedback:ne,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(n.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((F||k)&&(!(p!=null&&p.records)||p.records.length===0))return D==="table"||D==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!L.id)return null;if(D==="custom")return ye(l);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(D)&&ve)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:F||k?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:ve})});if(D==="table"||D==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.TableVisual,{card:L,data:W,comparisonMetadata:(ee=p==null?void 0:p.metadata)==null?void 0:ee.comparisonMetadata,paginationMetadata:z,onPaginationChange:Le,onSortChange:ae,isLoading:F||k})});if(D==="pivotTable"&&Ie)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.PivotTableTanstack,{card:L,data:Ie.data,options:Ie.options,onAggregationChange:Se=>{const fe=n.handleAggregationChange(Se,l.config),De={...l,config:fe};$(De),U(De)},onAggregationLabelChange:Se=>{const fe=n.handleAggregationLabelChange(Se,l.config),De={...l,config:fe};$(De),U(De)}})});if(D==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.AggregateTable,{card:L,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:z,onPaginationChange:Le,onAggregationChange:Se=>{const fe=n.handleAggregationChange(Se,l.config),De={...l,config:fe};$(De),U(De)},isLoading:F||k})})}return e.jsxs(n.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none bg-card text-card-foreground",s),style:{...u.cardFrameStyle,...a},...r,children:[(F||k)&&(p==null?void 0:p.records)&&p.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),o&&e.jsxs(n.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:u.cardGutterStyle,children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(n.EditableText,{value:l.title,onSave:ee=>$({...l,title:ee}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:l}),e.jsx(Me.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(fr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(l.description||"").trim(),onSave:ee=>$({...l,description:ee.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),S&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:S.title||S.column,onSave:ee=>B({...S,title:ee}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:S})]})]}),d&&l.inlineFilters&&l.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:u.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:l,sheetId:v||"",inlineFilterValues:x,setInlineFilterValue:ee=>w(l.id,ee),removeInlineFilterValue:ee=>A(l.id,ee)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col px-4"),style:u.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:K()}),n.isCardSummaryVisibleOnCard(L)&&e.jsx("div",{className:"pt-3",children:e.jsx(n.CardSummary,{card:L,mode:"editor"})})]}),e.jsx(n.FeedbackDialog,{open:f,onOpenChange:m,feedbackData:Ae,showDebugInfo:!0})]})}const as=({language:s,value:a,onChange:r,readonly:l})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:l,embedded:!0}),gr=()=>e.jsxs(n.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.DialogTitle,{children:"Customize Card"})}),e.jsxs(n.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),br=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:l,onCodeChange:u})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{language:"json",value:r,onChange:l})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{language:"javascript",value:s,onChange:u})})]}),jr=({error:s,hasCardCustomConfig:a,onReset:r,onApply:l,onClose:u})=>e.jsxs(n.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:r,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:l,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:u,variant:"outline",children:"Close"})]});function vr({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[l,u]=C.useState(!1),[c,o]=C.useState(""),[d,i]=C.useState(""),[x,h]=C.useState(""),[v,f]=C.useState(""),m=t.useEditorStore(j=>j.card),g=Me.useEffectiveEditorCardType(),y=t.useEditorStore(j=>j.card.customCfg),b=y?JSON.stringify(y,null,2):"",w=C.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:A}=n.useEditorCardQuery(w),{data:B}=n.useTopoJson(m),{setCardCustomCfg:S,setCustomVisualCode:E}=t.useEditorActions(),I=j=>{var O,D;return JSON.stringify({...j,data:{...j.data,datasets:(D=(O=j.data)==null?void 0:O.datasets)==null?void 0:D.map(L=>({...L,data:[]}))}},null,2)},T=()=>{var O,D;if(!((O=A==null?void 0:A.records)!=null&&O.length))return;const j=n.createChartConfig({card:m,data:A.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:B});if(j){o(I(j)),h(((D=m.preferences)==null?void 0:D.customVisualCode)||"");const L=n.merge(j,y);i(I(L))}},N=()=>{try{if(x&&E(x),d){const j=JSON.parse(d),O=n.getObjectDiff(JSON.parse(c),j);S(O),f("")}}catch{f("Invalid JSON configuration")}},M=Object.keys(y||{}).length===0;return e.jsxs(n.Dialog,{open:l,onOpenChange:u,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:T,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",M?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(n.Settings,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{tooltip:"Customize Visual",onClick:T,className:t.cn(M?"":"text-green-600 hover:text-green-700",a),children:e.jsx(n.Settings,{className:"h-4 w-4"})})}),e.jsxs(n.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(gr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(Vn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(br,{customCode:x,cardCustomCfgString:b,mergedConfig:d,onConfigChange:j=>i(j??""),onCodeChange:j=>h(j??"")})]}),e.jsx(jr,{error:v,hasCardCustomConfig:!!y,onReset:()=>{i(c),S(null)},onApply:N,onClose:()=>u(!1)})]})]})}function yr(s){let a=0;for(let l=0;l<s.length;l++)a=s.charCodeAt(l)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function Nr(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function fs({chartType:s,chartName:a,isCustom:r=!1,className:l="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,l);const u=n.getAutoDetectedChartIcon(a);if(u)return C.cloneElement(u,{className:l});const c=Nr(a),o=yr(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",l),style:{backgroundColor:o},children:c})}function Cr({isStarred:s,onClick:a,className:r}){const l=u=>{u.stopPropagation(),u.preventDefault(),a(u)};return e.jsx("button",{type:"button",onClick:l,className:t.cn("flex items-center justify-center rounded-control p-0.5 transition-all","hover:bg-muted/80",r),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(n.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function pn({chartType:s,chartName:a,isCustom:r=!1,pluginName:l,isStarred:u,showStar:c=!0,isSelected:o=!1,onSelect:d,onToggleStar:i}){return e.jsxs("div",{className:"group relative",children:[c&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",u?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(Cr,{isStarred:u,onClick:()=>i()})}),r&&l&&e.jsx("div",{className:"absolute right-1 top-1 z-10",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",children:l})]})}),e.jsxs("button",{type:"button",onClick:d,"aria-pressed":o,className:t.cn("flex w-full flex-col items-center justify-center gap-1.5 rounded-control border border-input bg-background px-2 py-2.5 transition-colors","hover:border-foreground/30 hover:bg-muted/40",o&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(fs,{chartType:s,chartName:a,isCustom:r,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:a})]})]})}const fn=[{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 zn({onChartSelect:s,onClose:a}){const[r,l]=C.useState(""),{starredCharts:u,isStarred:c,toggleStar:o}=n.useStarredChartsStore(),{data:d=[],isLoading:i}=n.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:h,setIsDevMode:v}=t.useEditorStore(j=>j.actions),f=t.useEditorStore(j=>j.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:y,setQueryConfig:b,replaceFrameCards:w,clearModeDrafts:A,initializeModeDrafts:B}=t.useEditorActions(),S=C.useMemo(()=>{if(!r)return fn;const j=r.toLowerCase();return fn.filter(O=>O.name.toLowerCase().includes(j))},[r]),E=C.useMemo(()=>{const j=d.filter(D=>D.componentType==="chart"&&D.pluginType!=="standard");if(!r)return j;const O=r.toLowerCase();return j.filter(D=>D.name.toLowerCase().includes(O))},[d,r]),I=j=>{m(null),h({}),y("builtin"),x(j),["custom","text","map"].includes(j)&&(v(!0),b(void 0)),s==null||s(j),a==null||a()},T=j=>{m(null),h({}),y("builtin"),b(void 0);const O=n.resolveMultiInputTypeFromVisual(j);if(O==="multiple"&&j.slots&&j.slots.length>0){A();const L=n.createCardsFromSlots(j.slots,j,f);w(L),L[0]&&B(L[0]),a==null||a();return}else x("custom"),g({type:"component",visualType:O,url:j.url,componentName:j.name,icon:j.icon,pluginChartType:j.chartType,minInputs:j.minInputs,maxInputs:j.maxInputs});s==null||s("custom",j),a==null||a()},N=j=>{const O={type:"default",id:j.id,name:j.name};o(O)},M=j=>{const O={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};o(O)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:j=>l(j.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),e.jsxs("div",{className:"max-h-[360px] overflow-y-auto pr-1",children:[S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:S.map(j=>e.jsx(pn,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:c("default",j.id),onSelect:()=>I(j.id),onToggleStar:()=>N(j)},j.id))}),E.length>0&&e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs("div",{className:"my-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Custom charts"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:E.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:E.map((j,O)=>e.jsx(pn,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:c("custom",j.name),onSelect:()=>T(j),onToggleStar:()=>M(j)},`${j.url}-${j.name}-${O}`))})]}),i&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),S.length===0&&E.length===0&&!i&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Sr({selectedChart:s,onChartChange:a}){var I,T,N,M;const r=t.useEditorStore(j=>j.card),l=t.useEditorStore(j=>j.frame),u=t.useEditorStore(j=>j.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:i}=t.useEditorActions(),x=C.useMemo(()=>n.findCustomVisualConfigCard(l,r),[l,r]),{manifest:h}=n.useCustomVisual(((I=x==null?void 0:x.customCardPreferences)==null?void 0:I.url)||""),v=C.useMemo(()=>{var j;return(j=h==null?void 0:h.visuals)==null?void 0:j.find(O=>{var D;return O.name===((D=x==null?void 0:x.customCardPreferences)==null?void 0:D.componentName)})},[h,(T=x==null?void 0:x.customCardPreferences)==null?void 0:T.componentName]),f=n.resolveMultiInputType(x,v)==="multiple",m=Me.useEffectiveEditorCardType(),g=f?m:s??r.type,y=(N=r==null?void 0:r.customCardPreferences)==null?void 0:N.componentName,b=(M=x==null?void 0:x.customCardPreferences)==null?void 0:M.componentName,w=f&&!!b,A=C.useMemo(()=>{const j=n.chartTypes.find(O=>O.id===g);return j?j.label:g==="custom"?y||"Custom Visual":"Select chart type"},[g,y]),B=C.useMemo(()=>{const j=n.chartTypes.find(O=>O.id===g);if(j){const O=j.icon;return e.jsx(O,{className:"h-4 w-4"})}if(g==="custom"&&y){const O=n.getAutoDetectedChartIcon(y);return O||e.jsx(fs,{chartName:y,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Ra,{className:"h-4 w-4"})},[g,y]);return{displayChartType:g,displayLabel:A,displayIcon:B,showBadge:w,badgeLabel:b,isMultiInputContext:f,handleChartSelect:j=>{a==null||a(j)},handleClearCustomVisual:j=>{j.stopPropagation();const O={...r,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([O]),o(),d(O),u&&i(!0),a==null||a("bar")}}}function wr({selectedChart:s,onChartChange:a,variant:r="ghost",className:l}){const[u,c]=C.useState(!1),{displayLabel:o,displayIcon:d,showBadge:i,badgeLabel:x,handleChartSelect:h,handleClearCustomVisual:v}=Sr({selectedChart:s,onChartChange:a}),f=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",l),children:[e.jsxs(t.Popover,{open:u,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:f?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":u,className:"flex h-9 w-full items-center justify-between gap-2 border-b border-border bg-card px-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:o})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",u&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":u,className:t.cn("w-full justify-between gap-2",r==="ghost"&&"border border-border/70 bg-background text-foreground/90",r==="outline"&&"border-border/70 bg-background text-foreground/90",r==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:m=>m.preventDefault(),children:e.jsx(zn,{onChartSelect:m=>h(m),onClose:()=>c(!1)})})]}),i&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(n.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:v,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}const jt={table:t.Table2,bar:n.ChartColumnIncreasing,line:n.ChartLine,stackedBar:n.ChartColumnStacked,stackedLine:n.MdStackedLineChart,scatter:n.ChartScatter,bubble:n.TbChartBubble,pie:n.ChartPie,doughnut:n.Donut,kpi:n.TiSortNumerically,treemap:n.TbChartTreemap,bullet:n.BulletChartIcon,funnel:n.TbChartFunnel,tornado:n.Tornado,heatmap:n.Grid3x3,range:n.ChartNoAxesGantt,radar:n.Radar,polarArea:n.PiChartPolar,text:n.BookType,map:n.Map},It={table:"Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},_n=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],qn=6;function Tr({selectedChart:s,onChartChange:a}){var A,B;const[r,l]=C.useState(!1),u=t.useEditorStore(S=>S.card),{setCardType:c,setCardPreferences:o}=t.useEditorStore(S=>S.actions),{setCardCustomCfg:d,setCustomCardPreferences:i,setQueryConfig:x,replaceFrameCards:h,clearModeDrafts:v,initializeModeDrafts:f}=t.useEditorActions(),{starredCharts:m}=n.useStarredChartsStore(),{data:g=[]}=n.useCustomVisualsQuery(),y=C.useMemo(()=>{const S=m.filter(N=>N.type==="default"?!0:g.some(M=>M.name===N.id)),E=new Set(S.map(N=>N.id)),I=_n.filter(N=>!E.has(N.id));return[...S.map(N=>({id:N.id,label:N.name,icon:N.type==="default"?jt[N.id]:void 0,isCustom:N.type==="custom",url:N.url})),...I.map(N=>({id:N.id,label:It[N.id]??N.id,icon:jt[N.id],isCustom:!1}))].slice(0,qn)},[m,g]),b=s==="custom"&&((A=u==null?void 0:u.customCardPreferences)==null?void 0:A.componentName);return y.some(S=>{var E;return S.isCustom?b&&((E=u==null?void 0:u.customCardPreferences)==null?void 0:E.componentName)===S.id:s===S.id})||(s==="custom"?(B=u==null?void 0:u.customCardPreferences)!=null&&B.componentName:It[s]),e.jsxs("div",{className:"px-4 pb-3 pt-4",children:[e.jsx("p",{className:"pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chart type"}),e.jsx($n,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function $n({selectedChart:s,onChartChange:a,compactMore:r=!1}){var I,T;const[l,u]=C.useState(!1),c=t.useEditorStore(N=>N.card),{setCardType:o,setCardPreferences:d}=t.useEditorStore(N=>N.actions),{setCardCustomCfg:i,setCustomCardPreferences:x,setQueryConfig:h,replaceFrameCards:v,clearModeDrafts:f,initializeModeDrafts:m}=t.useEditorActions(),{starredCharts:g}=n.useStarredChartsStore(),{data:y=[]}=n.useCustomVisualsQuery(),b=((I=c==null?void 0:c.customCardPreferences)==null?void 0:I.componentName)??null,w=C.useMemo(()=>{const N=g.filter(L=>L.type==="default"?!0:y.some(R=>R.name===L.id)),M=new Set(N.map(L=>L.id)),j=_n.filter(L=>!M.has(L.id)),O=[...N.map(L=>({id:L.id,label:L.name,icon:L.type==="default"?jt[L.id]:void 0,isCustom:L.type==="custom",url:L.url})),...j.map(L=>({id:L.id,label:It[L.id]??L.id,icon:jt[L.id],isCustom:!1}))];if(!O.some(L=>L.isCustom?s==="custom"&&L.id===b:L.id===s))if(s==="custom"&&b){const L=y.find(R=>R.name===b);L&&O.unshift({id:L.name,label:L.name,icon:void 0,isCustom:!0,url:L.url})}else s&&jt[s]&&O.unshift({id:s,label:It[s]??s,icon:jt[s],isCustom:!1});return O.slice(0,qn)},[g,y,s,b]),A=s==="custom"&&b,B=N=>{if(N.isCustom){const M=y.find(D=>D.name===N.id);if(!M)return;i(null),d({}),h(void 0);const j=n.resolveMultiInputTypeFromVisual(M);if(j==="multiple"&&M.slots&&M.slots.length>0){f();const D=n.createCardsFromSlots(M.slots,M,c);v(D),D[0]&&m(D[0]);return}o("custom"),x({type:"component",visualType:j,url:M.url,componentName:M.name,icon:M.icon,pluginChartType:M.chartType,minInputs:M.minInputs,maxInputs:M.maxInputs}),a("custom");return}a(N.id)},S=w.some(N=>{var M;return N.isCustom?A&&((M=c==null?void 0:c.customCardPreferences)==null?void 0:M.componentName)===N.id:s===N.id}),E=S?"More":s==="custom"?((T=c==null?void 0:c.customCardPreferences)==null?void 0:T.componentName)||"Custom":It[s]||"More";return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex h-7 items-center overflow-hidden rounded-control border border-input bg-background",children:w.map(N=>{var O;const M=N.icon,j=N.isCustom?A&&((O=c==null?void 0:c.customCardPreferences)==null?void 0:O.componentName)===N.id:s===N.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>B(N),"aria-label":N.label,"aria-pressed":!!j,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",j&&"bg-foreground/[0.08] font-medium text-foreground"),children:[M?e.jsx(M,{className:"h-3.5 w-3.5"}):e.jsx(fs,{chartName:N.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:N.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:N.label})]},`${N.isCustom?"custom":"default"}-${N.id}`)})}),e.jsxs(t.Popover,{open:l,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":E,className:t.cn("inline-flex h-7 items-center gap-1 rounded-control transition-colors hover:bg-muted/50",r?"w-7 justify-center":"px-2 text-[12px]",!r&&(S?"text-muted-foreground":"text-foreground")),children:[!r&&e.jsx("span",{className:"truncate",children:E}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",l&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:N=>N.preventDefault(),children:e.jsx(zn,{onChartSelect:N=>{a(N),u(!1)},onClose:()=>u(!1)})})]})]})}function Er(){const s=t.useEditorStore(i=>{var x,h;return(h=(x=i.card.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:r,setCardPreferences:l}=t.useEditorStore(i=>i.actions),u=i=>{if(r(i),a!=="bullet")return;const x=i==="y"?"horizontal":"vertical",h=t.useEditorStore.getState().card.preferences,v={...h||{},bulletConfig:{...(h==null?void 0:h.bulletConfig)||{},orientation:x}};l(v)};function c(){const i=s??"x",x=()=>{u(i==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:i==="x"?e.jsx(ts,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})})}function o(){const i=()=>{u(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:i,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(ts,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})})}function d(){const i=s??"y",x=()=>{u(i==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:i==="y"?e.jsx(es,{className:"h-3.5 w-3.5"}):e.jsx(ts,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():a==="bullet"?d():c()})}function gs({className:s,triggerVariant:a="icon",label:r="Display Options"}){var y,b,w,A,B,S,E,I,T,N;const l=t.useEditorStore(M=>M.card),{setCardPreferences:u,updateCardInFrame:c,setCard:o}=t.useEditorActions(),[d,i]=C.useState(!1),x=((b=(y=l.preferences)==null?void 0:y.displayOptions)==null?void 0:b.showFilterInfo)??!0,h=((A=(w=l.preferences)==null?void 0:w.displayOptions)==null?void 0:A.showCardToolbar)??!0,v=((S=(B=l.preferences)==null?void 0:B.displayOptions)==null?void 0:S.showChrome)??!0,f=((I=(E=l.preferences)==null?void 0:E.displayOptions)==null?void 0:I.allowScroll)??!0,m=((N=(T=l.preferences)==null?void 0:T.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,g=(M,j)=>{var L;const O={...l.preferences,displayOptions:{...(L=l.preferences)==null?void 0:L.displayOptions,[M]:j}};u(O);const D={...l,preferences:O};o(D),c(D)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:a==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{className:"h-7 w-7 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"Display Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:M=>{g("showFilterInfo",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:M=>{g("showCardToolbar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:v,onCheckedChange:M=>{g("showChrome",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:f,onCheckedChange:M=>{g("allowScroll",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:M=>{g("showInlineFilterBar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function bs({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){var E,I,T;const[l,u]=C.useState(!1),c=t.useEditorStore(N=>N.card),o=t.useEditorStore(N=>N.selectedConnectionId),{tokenProps:d}=n.useSemaphorContext(),{setCard:i}=t.useEditorActions(),x=t.useDashboardStore(N=>N.actions.removeCardInlineFilterValue),h=t.useDashboardStore(N=>N.actions.setCardInlineFilterValue),v=t.useEditorStore(N=>N.actions.removeCardInlineFilterValue),f=t.useEditorStore(N=>N.actions.setCardInlineFilterValue),m=t.useDashboardStore(N=>N.isVisualEditing),g=(c==null?void 0:c.inlineFilters)||[],y=((I=(E=d==null?void 0:d.params)==null?void 0:E.calendarContext)==null?void 0:I.tz)||((T=d==null?void 0:d.params)==null?void 0:T.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(N){var z,_,q,W,$,U,se;const M=((q=(_=(z=c==null?void 0:c.dataSource)==null?void 0:z.selectedEntities)==null?void 0:_[0])==null?void 0:q.database)||"",j=N.qualifiedFieldName||N.name;if(g.find(ie=>n.doesStoredFilterMatchField(ie,N)))return;const D=N.qualifiedFieldName?N.qualifiedFieldName.split(".").slice(0,-1).join("."):N.qualifiedEntityName||N.entityName,R=t.fmt(N.name),p=n.buildFilterFieldMeta(N),F=n.buildFilterSemanticContext(c==null?void 0:c.dataSource,{connectionId:o||((W=c==null?void 0:c.dataSource)==null?void 0:W.connectionId),connectionType:($=c==null?void 0:c.dataSource)==null?void 0:$.connectionType}),k=n.isCalculatedFilterField(p),P=!!(((U=c==null?void 0:c.dataSource)==null?void 0:U.mode)==="semanticDomain"&&((se=F==null?void 0:F.selectedEntities)!=null&&se.length||F!=null&&F.semanticDomainId)),V={id:t.v4(),column:j,title:N.label||N.name,dataType:N.dataType,table:N.entityName||"",database:M,qualifiedTableName:D,connectionId:o||"",operation:"in",sql:k||P?"":n.getDefaultFilterSql(N.dataType,D,R),fieldMeta:p,semanticContext:F,width:250};i({...c,inlineFilters:[...g,V]})}function w(N){const M=g.filter(j=>j.id!==N);i({...c,inlineFilters:M}),m?v(c.id,N):x(c.id,N)}function A(N,M){const j=g.map(R=>R.id===N?{...R,...M}:R);if(i({...c,inlineFilters:j}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const D=j.find(R=>R.id===N);if(!D)return;const L=t.buildFilterValueFromDefaults(D,y);L?m?f(c.id,L):h(c.id,L):m?v(c.id,N):x(c.id,N)}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 S=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",S&&"w-full",s),children:e.jsxs(t.Popover,{open:l,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:S?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(on,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(on,{className:"h-3.5 w-3.5"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",S&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(n.DndContext,{collisionDetection:n.closestCenter,children:e.jsx(n.SortableContext,{items:[],strategy:n.verticalListSortingStrategy,children:e.jsx(n.FieldsList,{context:"inline-filter",onFieldSelect:b,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(N=>e.jsx(Ir,{filter:N,onUpdate:M=>A(N.id,M),onRemove:()=>w(N.id)},N.id))})]})]})})]})})}function Ir({filter:s,onUpdate:a,onRemove:r}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(n.CustomFilterPopover,{filter:s,variant:"inline",onAccept:l=>a(l),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(n.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:r,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const kr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function Dr(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const Ar={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function qt(s,a){return`${s}:${a}`}function Mr(s,a,r){const l=new Set(r.filter(c=>c.target!=="sql_param").map(c=>qt(c.controlId,c.target))),u=a.map(c=>{const o=n.getCompatibleBindingTargetOptions({card:s,control:c}).map(h=>h.value),d=Ar[c.type],x=[...d?[d]:[],...o.filter(h=>h!==d)].find(h=>!l.has(qt(c.id,h)));return x?{controlId:c.id,target:x}:null}).find(Boolean);return u?{controlId:u.controlId,target:u.target,mapping:{}}:null}function Lr({card:s,dashboardControls:a,bindings:r,onChange:l,availableFieldChoices:u,availableMetricChoices:c,suppressTransientStaleState:o=!1}){const d=[...a,...s.controls||[]],[i,x]=C.useState({}),h=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),v=n.getBindingTargetSuggestions(s),f=new Set(r.map(B=>qt(B.controlId,B.target))),m=d.some(B=>n.getCompatibleBindingTargetOptions({card:s,control:B}).some(S=>!f.has(qt(B.id,S.value)))),g=o?0:r.reduce((B,S)=>{const E=y(S.target),I=Object.values(S.mapping).filter(T=>{const N=S.target==="config_metric_selector"||S.target==="config_field_selector"?typeof T=="string"?T:T==null?void 0:T.id:typeof T=="string"?T:void 0;return typeof N=="string"&&!E.some(M=>M.value===N)}).length;return B+I},0);function y(B){var S,E,I,T;switch(B){case"config_metric_selector":return c?c.filter(N=>!!N.target).map(N=>({value:N.target.id,label:N.target.label||N.option.label,target:N.target})):((E=(S=s.config)==null?void 0:S.metricColumns)==null?void 0:E.map(N=>({value:N.id,label:N.label||N.id,target:N})))||[];case"config_field_selector":return u?u.filter(N=>!!N.target).map(N=>({value:N.target.id,label:N.target.label||N.option.label,target:N.target})):((T=(I=s.config)==null?void 0:I.groupByColumns)==null?void 0:T.map(N=>({value:N.id,label:N.label||N.id,target:N})))||[];case"config_aggregation":return(v.config_aggregation||[]).map(N=>({value:N,label:N}));case"config_grain":return(v.config_grain||[]).map(N=>({value:N,label:N.charAt(0).toUpperCase()+N.slice(1)}));default:return[]}}const b=(B,S)=>{l(r.map((E,I)=>I!==B?E:S(E)))},w=B=>{l(r.filter((S,E)=>E!==B))},A=()=>{const B=Mr(s,d,r);B&&l([...r,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=h.map(({controlId:S,paramId:E})=>{const I=d.find(T=>T.id===S);return I?{id:S,paramId:E,label:I.label,reference:`[[param.${E}]]`}:{id:S,paramId:E,label:S,reference:`[[param.${E}]]`}});return e.jsx("div",{className:"space-y-2",children:B.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):B.map(S=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:S.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:S.reference}),e.jsx(n.CopyButton,{text:S.reference,ariaLabel:`Copy ${S.reference}`})]})]})},`${S.id}:${S.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(n.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,r.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is not using any controls yet."}):r.map((B,S)=>{const E=v[B.target]||[],I=d.find(p=>p.id===B.controlId),T=I?n.ensureManualSource(I):null,N=(T==null?void 0:T.source.kind)==="manual"?T.source.options:[],M=y(B.target),j=Array.from(new Set([...N.map(p=>p.value),...Object.keys(B.mapping)])).map(p=>{const F=N.find(k=>k.value===p);return{value:p,label:(F==null?void 0:F.label)||p}}),O=`${B.controlId}-${B.target}-${S}`,D=i[O]??S===0,L=Object.keys(B.mapping).length,R=I!=null&&I.type?kr[I.type]||I.type:null;return e.jsxs(n.Collapsible,{open:D,onOpenChange:p=>x(F=>({...F,[O]:p})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[D?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(n.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(I==null?void 0:I.label)||"Control"}),R?e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:R}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:L>0?`${L} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>w(S),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]}),e.jsx(n.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:j.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"Add choices to this control first so you can decide what each choice changes in the card."}):M.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No matching targets are available for this binding yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs",children:"Map each choice"}),e.jsx("div",{className:"space-y-2",children:j.map(p=>{const F=B.mapping[p.value],k=B.target==="config_metric_selector"||B.target==="config_field_selector"?typeof F=="string"?F:F==null?void 0:F.id:typeof F=="string"?F:void 0,P=!o&&typeof k=="string"&&!M.some(_=>_.value===k),V=Dr(F,k),z=k&&P?[...M,{value:k,label:"Needs remap",target:F}]:M;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:p.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:k||"__none__",onValueChange:_=>b(S,q=>{if(q.target==="config_metric_selector"){const $={...q.mapping};if(_==="__none__")delete $[p.value];else{const U=z.find(se=>se.value===_);U!=null&&U.target?$[p.value]=U.target:delete $[p.value]}return{...q,mapping:$}}if(q.target==="config_field_selector"){const $={...q.mapping};if(_==="__none__")delete $[p.value];else{const U=z.find(se=>se.value===_);U!=null&&U.target?$[p.value]=U.target:delete $[p.value]}return{...q,mapping:$}}const W={...q.mapping};return _==="__none__"?delete W[p.value]:W[p.value]=_,{...q,mapping:W}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),z.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),P?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(n.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",V?` · Previously: ${V}`:""]})]}):null]})]},`${B.controlId}-${B.target}-${p.value}`)})}),E.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",E.join(", ")]})]})})]},O)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(n.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Fr=[];function Kn({className:s,triggerVariant:a="icon",label:r="Controls"}){var D,L;const{handleOpenChange:l,preventPassiveDismissDuringCreate:u,resolvedOpen:c,setIsCreateFlowActive:o}=Me.useCreateFlowOverlayState({}),d=t.useEditorStore(R=>R.card),i=t.useEditorStore(R=>R.frame),x=t.useDashboardStore(R=>R.dashboard),v=t.useDashboardStore(R=>R.dashboard.controls)||Fr,{setCard:f,updateCardInFrame:m}=t.useEditorActions(),[g,y]=C.useState(null);C.useEffect(()=>{c&&!g&&(d!=null&&d.id)&&y(d.id)},[d==null?void 0:d.id,c,g]),C.useEffect(()=>{!c&&g!==null&&y(null)},[c,g]);const b=C.useMemo(()=>g?(i==null?void 0:i.cards.find(R=>R.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,i==null?void 0:i.cards,g]),w=(b==null?void 0:b.controls)||[],A=b?n.collectDashboardControlIds(x,{excludeCardId:b.id}):v.map(R=>R.id),B=((b==null?void 0:b.controlBindings)||[]).filter(R=>R.target!=="sql_param"),S=n.buildCardControlUsageById({card:b,controls:w}),E={choices:n.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((D=b==null?void 0:b.config)==null?void 0:D.groupByColumns)||[]).map(R=>[R.id,R]))},I={choices:n.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((L=b==null?void 0:b.config)==null?void 0:L.metricColumns)||[]).map(R=>[R.id,R]))},T=E.choices.map(R=>({option:R,target:E.targetMap[R.value]})),N=I.choices.map(R=>({option:R,target:I.targetMap[R.value]})),M=(R,p)=>{if(!b)return;const F=(p==null?void 0:p.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:p.oldId,newId:p.newId}):(p==null?void 0:p.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:p.controlId}):b,k={...F,controls:R,controlBindings:n.syncStructuralBindingsWithControls(F.controlBindings,R)};m(k),(d==null?void 0:d.id)===k.id&&f(k)},j=R=>{if(!b)return;const p={...b,controlBindings:n.mergeConfigBindingsWithSqlParamBindings(R,b.controlBindings)};m(p),(d==null?void 0:d.id)===p.id&&f(p)},O=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",O&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:O?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(w.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),w.length+B.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:w.length+B.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":w.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),w.length+B.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:w.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),b!=null&&b.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Me.ControlDefinitionListEditor,{scope:"card",card:b,controls:w,reservedControlIds:A,usageByControlId:S,availableFieldChoices:T,availableMetricChoices:N,onCreateFlowActiveChange:o,onChange:(R,p,F)=>M(R,F),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),b?e.jsx(Lr,{card:b,dashboardControls:v,bindings:B,onChange:j,availableFieldChoices:T,availableMetricChoices:N}):null]})})]})]})})}function Gn({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:l=!0,showDisplayOptions:u=!0}={}){const c=t.useEditorStore(m=>m.card),o=t.useEditorStore(m=>{var g,y;return(y=(g=m.card)==null?void 0:g.preferences)==null?void 0:y.chartOptions}),d=n.getChartGridStyle(o),{setChartGrid:i}=t.useEditorActions();function x(){const m=["xy","none","x","y"],y=(m.indexOf(d)+1)%m.length;i(m[y])}const h=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(c.type),v=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(c.type);return h||v||r||l||u?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[h&&e.jsx(e.Fragment,{children:e.jsx(Er,{})}),v&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:x,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(hs,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx($t,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(bs,{}),l&&e.jsx(Kn,{}),u&&e.jsx(gs,{})]}):null}function Rr({visible:s}){const a=t.useDashboardStore(o=>o.selectedFrameId),r=n.useManagementStore(o=>o.selectedVisual),l=t.useEditorStore(o=>o.frame),c=!!!(l!=null&&l.visualId||r!=null&&r.id)&&!!a;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 Or({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var F,k,P,V,z;const l=t.useEditorStore(_=>_.frame),u=t.useEditorStore(_=>_.card),c=t.useEditorStore(_=>_.editorContext),o=(c==null?void 0:c.type)==="documentSection",{setFrame:d,setActiveTabCardId:i,setCard:x,updateCardInFrame:h,clearModeDrafts:v,initializeModeDrafts:f}=t.useEditorActions(),{manifest:m}=n.useCustomVisual(((F=r==null?void 0:r.customCardPreferences)==null?void 0:F.url)||""),g=(k=m==null?void 0:m.visuals)==null?void 0:k.find(_=>{var q;return _.name===((q=r==null?void 0:r.customCardPreferences)==null?void 0:q.componentName)}),b=n.resolveMultiInputType(r,g)==="multiple",w=(g==null?void 0:g.minInputs)??((P=r==null?void 0:r.customCardPreferences)==null?void 0:P.minInputs)??1,A=(g==null?void 0:g.maxInputs)??((V=r==null?void 0:r.customCardPreferences)==null?void 0:V.maxInputs),B=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:r,isMultiInputVisual:b}),[l,r,b]),S=b?B.filter(Boolean).length:l.cards.length,E=o?!1:A?S<A:!0,I=S>Math.max(w||1,1),T=!!((z=r==null?void 0:r.customCardPreferences)!=null&&z.dataInputCardIds),N=(_,q)=>{_.dataTransfer.setData("tabIndex",q.toString())},M=_=>{_.preventDefault()},j=(_,q)=>{const W=_.dataTransfer.getData("tabIndex");if(W===q.toString())return;const $=Array.from(l.cards),[U]=$.splice(parseInt(W),1);$.splice(q,0,U),d({...l,cards:$})};function O(_){const q=(r==null?void 0:r.id)===_;if(!(T&&q?l.cards.length>1:I))return;let $=l.cards.filter(le=>le.id!==_);b&&!T&&($=n.reindexSlotCards($));const U=$[0],se={...l,cards:$,activeCardId:U.id},ie=_===u.id;ie&&v(),d(se),i(U.id),x(U),ie&&f(U)}function D(_,q){if(!E)return;const W={...l,cards:[...l.cards,q],activeCardId:_.id};d(W),i(q.id)}function L(){if(o)return;if(b&&(r==null?void 0:r.id)===u.id){R(u);return}const _={...u,id:t.v4(),title:`${u.title} Copy`,tabTitle:`${u.tabTitle||u.title} Copy`,customCardPreferences:u.customCardPreferences?{...u.customCardPreferences,slotIndex:b?Math.max(-1,...B.map((q,W)=>n.getSlotIndexForCard(q,W)))+1:u.customCardPreferences.slotIndex}:void 0};D(u,_)}function R(_){var ie;if(o||!E)return;let q=b?"table":"bar",W="Title",$="";const U=b?Math.max(-1,...B.map((le,de)=>n.getSlotIndexForCard(le,de)))+1:S;if(b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)){const le=n.getSlotDefinitionForIndex(g.slots,U);le&&(q=n.getSlotExpectedChartType(le),W=le.label||`Tab ${U+1}`,$=le.description||"")}const se={dataSource:_.dataSource,connectionId:_.connectionId,lastSelectedDatabase:_.lastSelectedDatabase,lastSelectedSchema:_.lastSelectedSchema,lastSelectedTable:_.lastSelectedTable,lastSelectedDatamodelId:_.lastSelectedDatamodelId,id:t.v4(),title:W,tabTitle:W,description:$,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:q,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:U}}};D(_,se)}function p(_,q){return _.cards.length===1&&(q.displayTab===!0||q.displayTab===void 0)||_.activeCardId!==q.id&&(q.displayTab===!0||q.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const W=q.displayTab===void 0?!1:!q.displayTab;x({...q,displayTab:W}),h({...q,displayTab:W})},children:q.displayTab===!0||q.displayTab===void 0?e.jsx(n.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(n.EyeOff,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{variant:"underline",className:"group flex h-9 items-center justify-start gap-1 overflow-x-auto rounded-none border-b-0 border-t border-border bg-background px-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[l.cards.map((_,q)=>{var ie,le;const W=b?n.getSlotIndexForCard(_,q):-1,$=b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)&&W>=0?n.getSlotDefinitionForIndex(g.slots,W):null,U=$?(Array.isArray($.expectedType)?$.expectedType[0]:$.expectedType)||"table":_.type,se=b&&((le=g==null?void 0:g.slots)==null?void 0:le.length)&&g.slots.every(de=>typeof de.position=="number"||typeof de.position=="string"&&!de.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!b&&!o,onDragStart:b||o?void 0:de=>N(de,q),onDragOver:b||o?void 0:M,onDrop:b||o?void 0:de=>j(de,q),className:t.cn("inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[5px] border px-2 text-[12px] font-normal text-muted-foreground transition-colors","mb-0 border-transparent pb-0","hover:bg-muted/40 hover:text-foreground","data-[state=active]:border-border data-[state=active]:bg-card data-[state=active]:text-foreground"),value:_.id,children:[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:n.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:$.label||`Tab ${W+1}`})]})}),e.jsx(t.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:$.label}),$.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:$.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[$.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray($.expectedType)?$.expectedType.join(" / "):$.expectedType}),$.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[p(l,_),e.jsx(n.Editable,{enabled:l.activeCardId===_.id,text:_.tabTitle||_.title,onSave:de=>{x({...u,tabTitle:de}),h({...u,tabTitle:de})},children:_.tabTitle||_.title},_.id)]}),!o&&l.activeCardId===_.id&&!se&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:de=>{de.stopPropagation(),L()}}),!o&&l.activeCardId===_.id&&(T&&(r==null?void 0:r.id)===_.id?l.cards.length>1:I)&&e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>O(_.id)})]},_.id)}),!o&&e.jsx(n.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>R(u),disabled:!E,children:e.jsx(n.Plus,{className:"h-3 w-3"})}),b&&e.jsxs(n.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-1 h-6 gap-1 rounded-[5px] px-2 text-[11px] data-[state=on]:bg-muted data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(n.EyeOff,{className:"h-3 w-3"}):e.jsx(n.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function it({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var ve,ye,K;const r=t.useEditorStore(Q=>Q.frame),l=t.useEditorStore(Q=>Q.card),[u,c]=C.useState(!1),o=C.useMemo(()=>n.findCustomVisualConfigCard(r,l),[r,l]),d=t.useEditorStore(Q=>Q.isSqlRunning);t.useEditorStore(Q=>Q.isDevMode);const{setFrame:i,setActiveTabCardId:x,setCard:h,setRunSql:v,mergeDraftsIntoCard:f,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[y,b]=C.useState({}),[w,A]=C.useState(()=>new Set),{authToken:B}=n.useSemaphorContext(),S=t.getTokenParams(B==null?void 0:B.accessToken),{compiledAppearance:E}=t.useAppearance(),I=C.useMemo(()=>n.buildCustomCardTheme(E),[E]),{getCard:T,manifest:N,isLoading:M}=n.useCustomVisual(((ve=o==null?void 0:o.customCardPreferences)==null?void 0:ve.url)||""),j=(ye=o==null?void 0:o.customCardPreferences)==null?void 0:ye.componentName,O=j?T(j):null,D=(K=N==null?void 0:N.visuals)==null?void 0:K.find(Q=>Q.name===j),L=n.resolveMultiInputType(o,D),R=u&&L==="multiple"&&!!o,p=C.useMemo(()=>n.getCustomVisualInputCards({frame:r,configCard:o,isMultiInputVisual:!0}).map(te=>(te==null?void 0:te.id)===l.id?l:te),[r,o,l]),F=C.useMemo(()=>n.buildSlotOrderedCards(p),[p]),k=C.useMemo(()=>{const Q=p.findIndex(te=>(te==null?void 0:te.id)===l.id);return Q<0?-1:n.getSlotIndexForCard(l,Q)},[p,l]),P=C.useMemo(()=>!o||L!=="multiple"||k<0?l.type:n.getEffectiveCardTypeForSlot(l,k,D==null?void 0:D.slots)??l.type,[o,L,k,l,D==null?void 0:D.slots]),V=C.useMemo(()=>R?{...l,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:P!==l.type?{...l,type:P}:l,[l,P,R]),{data:z,isLoading:_,isFetching:q,isError:W}=n.useEditorCardQuery(V),$=C.useCallback((Q,te)=>{const xe=n.normalizeMultiInputPayload(te);b(pe=>({...pe,[Q]:xe}))},[]),U=C.useCallback((Q,te)=>{A(xe=>{const pe=new Set(xe);return te?pe.add(Q):pe.delete(Q),pe})},[]),se=w.size>0,ie=t.useInteractionStore(Q=>Q.interactionStates),le=t.useDashboardStore(Q=>{var te;return(te=Q.dashboard)==null?void 0:te.id}),de=t.useDashboardStore(Q=>Q.dashboard.filters),me=t.useDashboardStore(Q=>Q.filterValues),ue=t.useDashboardStore(Q=>Q.selectedSheetId),Ne=t.useEditorStore(Q=>Q.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),we=t.useEditorStore(Q=>Q.actions.setCardInlineFilterValue),Te=t.useEditorStore(Q=>Q.actions.removeCardInlineFilterValue),Z=C.useMemo(()=>o?n.buildInlineFilterNodes({card:o,sheetId:ue||"",inlineFilterValues:Ne,setInlineFilterValue:Q=>we(o.id,Q),removeInlineFilterValue:Q=>Te(o.id,Q)}):[],[o,ue,Ne,we,Te]),{cardFilters:je,cardFilterValues:Ie}=C.useMemo(()=>o?n.calculateContextAwareFilters({card:o,interactionStates:ie,currentDashboardId:le,filters:de,filterValues:me,selectedSheetId:ue}):{cardFilters:[],cardFilterValues:[]},[o,ie,le,de,me,ue]);function ne(Q){const te=r.cards.find(xe=>xe.id===Q);te&&(ct.flushPendingEditorDrafts(),f(),Ae(Q),x(Q),m(),g(te))}function Ae(Q){const te=t.useEditorStore.getState().card,xe=t.useEditorStore.getState().frame,pe={...xe,cards:xe.cards.map(ee=>ee.id===te.id?te:ee),activeCardId:Q};i(pe);const Fe=pe.cards.find(ee=>ee.id===Q);Fe.sql&&v(!0),h(Fe)}function Le(){if(M)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!O)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 te=F.map((xe,pe)=>n.getEffectiveCardTypeForSlot(xe,pe,D==null?void 0:D.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[p.map((xe,pe)=>{if(!xe)return null;const Fe=n.getSlotIndexForCard(xe,pe),ee=n.getEffectiveCardTypeForSlot(xe,Fe,D==null?void 0:D.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:U,onDataChange:$,card:xe,effectiveCardType:ee},`${xe.id}-${Fe}`)}),se&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",se&&"opacity-50"),children:e.jsx(C.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(O,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:o,slotOrderedCards:F,slotTypes:te,multiInputData:y,params:S,theme:I,filters:je,filterValues:[...Ie||[],...Ne||[]],inlineFilters:Z})})})})]})}function ae(){var Q;return R?Le():s&&(a||!_&&!q&&!W)?s({card:l,data:z,isLoading:_,isFetching:q,isError:W}):l.type==="kpi"?_||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(Rr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:l,data:z==null?void 0:z.records,isPending:_||q,isError:W,comparisonMetadata:(Q=z==null?void 0:z.metadata)==null?void 0:Q.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(l)&&e.jsx(n.CardSummary,{card:l,mode:"editor"})]})}):l.type==="text"?_||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(n.TextCard,{isLoading:d,card:l,data:z==null?void 0:z.records})})})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(Vn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ne,value:r.activeCardId,className:"flex grow flex-col gap-2",children:[R?e.jsx("div",{className:"mt-0 grow",children:ae()}):r.cards.map(Q=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:Q.id,children:ae()},Q.id)),e.jsx(Or,{isPreviewMode:R,onPreviewToggle:c,configCard:o})]})}function Pr({onClick:s,className:a}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",a),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Un({fallbackPreview:s,records:a,title:r,isInspectorOpen:l,onInspectorOpenChange:u}){var L;const c=t.useEditorStore(R=>R.card),o=t.useEditorStore(R=>R.actions.setCard),d=t.useEditorStore(R=>R.actions.updateCardInFrame),i=t.normalizeDynamicRendererSource((L=c.dynamicCardPreferences)==null?void 0:L.rendererCode),[x,h]=C.useState(i),[v,f]=C.useState(i);C.useEffect(()=>{h(i),f(i)},[i,c.id]);const m=C.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),g=C.useMemo(()=>t.validateDynamicRendererSource(m),[m]),y=!!i,b=C.useMemo(()=>{var R;return t.buildCardWithVisualizationMode(c,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((R=c.dynamicCardPreferences)==null?void 0:R.artifactId)||c.id,title:r||c.title})},[c,v,r]),w=!!v,A=m!==v,B=v!==i,S=!m||!g.valid||A||B,E=m?g.valid?A?"Unapplied changes":"Pending save":"Needs attention":"Draft",I=!m||A||B?"outline":"destructive",T=m?g.valid?A?"The preview still reflects the last applied code until you apply this draft.":B?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function N(){if(!g.valid){n.ue.error(g.error||"Visual code is invalid.");return}f(m),n.ue.success("Dynamic preview updated.")}function M(){h(v)}function j(){var p;const R=t.buildCardWithVisualizationMode(c,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((p=c.dynamicCardPreferences)==null?void 0:p.artifactId)||t.v4(),title:r||c.title});o(R),d(R),u(!1),n.ue.success(v?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function O(){h(i),f(i),u(!1)}function D(){h(""),f("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:y?e.jsx(n.PersistedDynamicVisual,{card:c,records:a,title:r,layoutMode:"fill",fallback:s},i||"applied-empty"):e.jsxs("div",{className:"flex h-full min-h-[280px] flex-col items-center justify-center gap-3 rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center",children:[e.jsx("div",{className:"flex size-10 items-center justify-center rounded-full border bg-background",children:e.jsx(n.CodeXml,{className:"text-muted-foreground"})}),e.jsxs("div",{className:"flex max-w-md flex-col gap-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"No applied dynamic visual yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open Customize, paste visual code, and apply it to preview the renderer here."})]}),e.jsx(Pr,{onClick:()=>u(!0)})]})}),e.jsx(n.Dialog,{open:l,onOpenChange:R=>{if(!R){O();return}u(!0)},children:e.jsxs(n.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(n.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(n.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(n.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),S&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:I,children:E})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{defaultSize:54,minSize:38,children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx("div",{className:"min-h-0 flex-1 bg-background p-4",children:w?e.jsx(n.PersistedDynamicVisual,{card:b,records:a,title:r,layoutMode:"fill",fallback:s},v||"preview-empty"):e.jsx("div",{className:"flex h-full min-h-[280px] items-center justify-center rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center text-sm text-muted-foreground",children:"Apply valid visual code to preview the dynamic visual here."})})})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:46,minSize:30,children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(n.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n.AlertDialog,{children:[e.jsx(n.AlertDialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{type:"button",size:"sm",variant:"ghost",className:"h-8 gap-1.5 px-2.5 text-xs",disabled:!y&&!m,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(n.AlertDialogContent,{children:[e.jsxs(n.AlertDialogHeader,{children:[e.jsx(n.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(n.AlertDialogDescription,{children:"This removes the saved dynamic renderer and switches the card back to built-in mode. The underlying query and built-in chart type will remain."})]}),e.jsxs(n.AlertDialogFooter,{children:[e.jsx(n.AlertDialogCancel,{children:"Cancel"}),e.jsx(n.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:D,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:M,disabled:!A,children:[e.jsx(ms.RotateCcw,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:N,disabled:!A||!g.valid,children:[e.jsx(n.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[T&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:T}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:x,onValueChange:R=>h(R||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(n.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:T||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:O,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:j,disabled:!B,children:"Accept changes"})]})]})]})})]})}function Hn({onCustomize:s}){const a=t.useEditorStore(x=>x.card),r=t.useEditorStore(x=>x.frame),l=t.useEditorStore(x=>x.actions.setIsShowingVisual),{setVisualizationMode:u,setDynamicCardPreferences:c}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const i=x=>{var h;x==="dynamic"&&!a.dynamicCardPreferences&&c(t.createEmptyDynamicCardPreferences(a.type,(h=a.preferences)==null?void 0:h.displayOptions)),u(x),l(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),i(d?"builtin":"dynamic")},className:"flex items-center justify-between gap-2 text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CodeXml,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{size:"xs",checked:d,onCheckedChange:x=>i(x?"dynamic":"builtin"),onClick:x=>x.stopPropagation()})]}),d&&s?e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),s()},className:"gap-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),"Customize Visual"]}):null]})}const Br={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Vt=50,Vr=[{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 gn(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),null}}function bt(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 zr(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Vt?{value:s}:{value:{...s,records:a.slice(0,Vt),previewMeta:{truncatedRecords:!0,displayedRecords:Vt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Vt} records of ${a.length}. Copy actions include full payload.`}}function Qn({sql:s,showCardDetails:a=!1,debugPayloads:r,className:l}){const[u,c]=C.useState(!1),[o,d]=C.useState(null),i=t.useEditorStore(j=>j.card),x=t.useEditorStore(j=>j.frame),h=t.useEditorStore(j=>j.isDevMode),v=t.useDashboardStore(j=>j.selectedSheetId),f=t.useDashboardStore(j=>{var O;return(O=j.dashboard)==null?void 0:O.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),y=C.useMemo(()=>({cardId:i.id||null,frameId:x.id||null,sheetId:v||null,dashboardId:f||null}),[i.id,x.id,v,f]),b=C.useMemo(()=>({queryRequest:r==null?void 0:r.queryRequest,queryResponse:r==null?void 0:r.queryResponse,cardConfig:i.config,dataSource:i.dataSource,columns:r==null?void 0:r.columns,dashboardFilters:r==null?void 0:r.dashboardFilters,cardMetadata:y}),[r==null?void 0:r.queryRequest,r==null?void 0:r.queryResponse,r==null?void 0:r.columns,r==null?void 0:r.dashboardFilters,i.config,i.dataSource,y]),w=a&&u&&!!r,A=C.useMemo(()=>[{label:"Card ID",value:i.id||""},{label:"Frame ID",value:x.id||""},{label:"Sheet ID",value:v||""},{label:"Dashboard ID",value:f||""}],[i.id,x.id,v,f]),B=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},S=j=>b[j]!==void 0,E=C.useMemo(()=>{if(!o)return null;const j=b[o];if(j===void 0)return null;const O=o==="queryResponse"?zr(j):{value:j},D=gn(O.value);return D?{target:o,title:bt(o),json:D,truncationMessage:O.truncationMessage}:null},[o,b]),I=E?E.title:"Preview Payload",T=async j=>{const O=b[j];if(O===void 0)return n.ue.error(`No ${bt(j).toLowerCase()} available`),!1;const D=gn(O);if(!D)return n.ue.error(`Unable to serialize ${bt(j).toLowerCase()}`),!1;try{return await Br.writeTextToClipboard(D)?(n.ue.success(`${bt(j)} copied`),!0):(n.ue.error("Clipboard is not available"),!1)}catch(L){return console.error("Failed to copy debug payload",L),n.ue.error(`Unable to copy ${bt(j).toLowerCase()}`),!1}},N=async()=>E?T(E.target):!1,M=j=>{if(b[j]===void 0){n.ue.error(`No ${bt(j).toLowerCase()} available`);return}d(j)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col pt-3",l),children:[!h&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:B,variant:"outline",size:"xs",children:[e.jsx(Ln,{className:"mr-1.5 h-3 w-3"}),"View in SQL Editor"]}),a&&e.jsxs(t.Button,{onClick:()=>c(!u),variant:"outline",size:"xs",children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),"Card Details"]})]}),u&&a&&e.jsx("div",{className:"mb-3 rounded-[6px] border border-border bg-card p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-[12px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 rounded-[3px] p-0",onClick:()=>c(!1),children:e.jsx(Me.CircleX,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:A.map(j=>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:j.label}),e.jsx(n.CopyButton,{text:j.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:j.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:j.value||"N/A"})]},j.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(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(n.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),I,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(n.DropdownMenuContent,{align:"start",className:"w-56",children:Vr.map(j=>e.jsx(n.DropdownMenuItem,{disabled:!S(j.target),onSelect:()=>M(j.target),className:t.cn(o===j.target&&"bg-accent"),children:j.label},`preview-${j.target}`))})]})}),E&&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:[E.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(n.CopyButton,{text:E.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:N}),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"]})]})]}),E.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:E.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(n.CodeHighlighter,{code:E.json,language:"json"})})]})]})]})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex h-7 shrink-0 items-center justify-between border-b border-border px-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-[12px] text-muted-foreground",children:"Generated query"})]}),e.jsx(n.CopyButton,{text:s,className:"h-5 w-5 rounded-[3px] px-0 text-muted-foreground hover:bg-muted hover:text-foreground"})]}),e.jsx("div",{className:"min-h-[80px] flex-1 px-3 py-2",children:e.jsx(t.CodeEditor,{value:s,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Executed SQL"})})]})]})}function rs({children:s,visualAsideControl:a,mode:r="both",isDynamicInspectorOpen:l,onDynamicInspectorOpenChange:u}){var Le;const c=n.useQueryClient(),o=t.useEditorStore(ae=>ae.frame),d=t.useEditorStore(ae=>ae.card),i=d.type==="table"||d.type==="detailTable",x=t.useEditorStore(ae=>ae.isDevMode),h=t.useEditorStore(ae=>ae.editorContext),v=(h==null?void 0:h.type)==="documentSection",f=t.useEditorStore(ae=>ae.isShowingVisual),m=t.useEditorStore(ae=>ae.actions.setIsShowingVisual),g=t.useDashboardStore(ae=>ae.isVisualEditing),{isConsoleMode:y}=n.useDashboardPreferences(),b=t.useEditorStore(ae=>ae.pythonStdOut),w=t.useEditorStore(ae=>ae.actions.setRunSql),A=Me.useEffectiveEditorCardType(),S=t.getVisualizationMode(d)==="dynamic",[E,I]=C.useState(!1),T=l??E,N=u??I,{setFrame:M,setCard:j,setActiveTabCardId:O,setCardPreferences:D,mergeDraftsIntoCard:L,clearModeDrafts:R,initializeModeDrafts:p,updatePageSize:F,setCardType:k}=t.useEditorActions(),P=C.useMemo(()=>A!==d.type?{...d,type:A}:d,[d,A]),{data:V,isLoading:z,isFetching:_,errorMessage:q,errorSql:W,refetch:$,queryKey:U,pagination:se}=n.useEditorCardQuery(P),ie=C.useRef(U);ie.current=U;const{handleDebugWithAssistant:le}=Bn(q,W),de=C.useMemo(()=>(V==null?void 0:V.records)||[],[V==null?void 0:V.records]),{cardFilterValues:me}=n.useCardFilterValues((d==null?void 0:d.id)??""),[ue,Ne]=C.useState(!1);C.useEffect(()=>{_||Ne(!1)},[_]),C.useEffect(()=>{i&&!f&&!x&&!y&&m(!0)},[y,x,i,f,m]);function we(ae,ve){var Q,te;const ye={...d,paginationConfig:{page:ae+1,pageSize:ve}};j(ye);const K={...o,cards:o.cards.map(xe=>xe.id===d.id?ye:xe)};M(K),d.sql&&((te=(Q=d.preferences)==null?void 0:Q.tablePrefs)!=null&&te.enableDevModePagination)&&w(!0)}function Te(ae){var Q,te,xe,pe,Fe;const ve=n.sortStateToSortByColumns(ae,(Q=d.config)==null?void 0:Q.metricColumns,(te=d.config)==null?void 0:te.groupByColumns,(xe=d.config)==null?void 0:xe.detailColumns),ye={...d,config:{...d.config||{},sortByColumns:ve}};j(ye);const K={...o,cards:o.cards.map(ee=>ee.id===d.id?ye:ee)};M(K),d.sql&&((Fe=(pe=d.preferences)==null?void 0:pe.tablePrefs)!=null&&Fe.enableDevModePagination)&&w(!0)}function Z(){var ve;const ae=JSON.stringify(V==null?void 0:V.records,null,2);typeof navigator>"u"||!((ve=navigator.clipboard)!=null&&ve.writeText)||navigator.clipboard.writeText(ae).catch(ye=>{console.error("Failed to copy JSON",ye)})}function je(){const ae=JSON.stringify(V==null?void 0:V.records,null,2),ve=new Blob([ae],{type:"application/json"}),ye=URL.createObjectURL(ve),K=document.createElement("a");K.href=ye,K.download=`${d.title}.json`,K.click()}function Ie(){const ve=[Object.keys(V==null?void 0:V.records.reduce((te,xe)=>({...te,...xe}),{})).join(","),...((V==null?void 0:V.records)||[]).map(te=>Object.values(te).join(","))].join(`
182
- `),ye=new Blob([ve],{type:"text/csv"}),K=URL.createObjectURL(ye),Q=document.createElement("a");Q.href=K,Q.download=`${d.title}.csv`,Q.click()}if(!d)return e.jsx(e.Fragment,{children:"No Active Card"});const ne=r==="both"||r==="toolbar",Ae=r==="both"||r==="canvas";return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",r==="toolbar"?"h-auto pb-1":"h-full pt-2"),children:[ne&&e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center gap-2 px-4",children:[f&&e.jsx("div",{className:"flex grow items-center gap-4",children:e.jsx("div",{className:"flex items-center gap-3",children:!v&&!S&&e.jsx($n,{selectedChart:d.type,onChartChange:ae=>k(ae),compactMore:!0})})}),!z&&!_&&!q&&(V==null?void 0:V.sql)&&e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"View executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",className:"w-[500px] p-0",children:e.jsx(Qn,{sql:V.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,me&&me.length>0&&e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(n.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(n.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:me.length})]})}),e.jsxs(n.HoverCardContent,{align:"end",className:"flex max-h-[400px] w-[500px] flex-col overflow-hidden p-0",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(t.CodeEditor,{value:JSON.stringify(me,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),e.jsx(n.IconButton,{tooltip:"Refresh",disabled:z||_,className:"h-7 w-7 px-0",onClick:()=>{if(Ne(!0),x){ct.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:ie.current,exact:!0}),w(!0)},0);return}$()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":ue})})}),!S&&e.jsx(Gn,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 gap-1.5 px-2 text-[12px]",a.isOpen&&"bg-muted/40 text-foreground"),children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),"Chart settings"]}),(x||y)&&i&&e.jsx(qr,{}),e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-56",children:[(x||y)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"View"}),e.jsxs(n.DropdownMenuItem,{onSelect:ae=>{ae.preventDefault(),m(!f)},className:"gap-2 text-[13px]",children:[e.jsx(t.Table2,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"flex-1",children:"Query output"}),!f&&e.jsx(t.Check,{className:"h-3.5 w-3.5 text-foreground",strokeWidth:2})]}),e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!S&&!["table","detailTable","custom"].includes(d.type)&&g&&e.jsx(vr,{triggerVariant:"menu",className:"w-full"}),e.jsx(bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Kn,{triggerVariant:"menu",className:"w-full"}),e.jsx(gs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Hn,{onCustomize:()=>N(!0)}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{onSelect:Ie,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{onSelect:je,className:"gap-2 text-[13px]",children:[e.jsx(wa,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Z,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]})]})]})]}),Ae&&(f?S?e.jsx(it,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Un,{fallbackPreview:e.jsx(it,{}),records:de,title:d.title,isInspectorOpen:T,onInspectorOpenChange:N})}):e.jsx(it,{}):e.jsxs(n.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[b&&e.jsxs(e.Fragment,{children:[e.jsx(n.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:b&&e.jsx(_r,{})}),e.jsx(n.ResizableHandle,{})]}),e.jsxs(n.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":b}),children:[Array.isArray(V==null?void 0:V.records)&&!q&&(x?e.jsx(pr,{data:V.records,card:P,paginationMetadata:se,onPaginationChange:we,onPageSizePreferenceChange:F,onSortChange:Te,isLoading:z||_}):V.records.length>0?e.jsx(n.TableVisual,{card:d,data:de,comparisonMetadata:(Le=V==null?void 0:V.metadata)==null?void 0:Le.comparisonMetadata,paginationMetadata:se,onPaginationChange:we,onSortChange:Te,isLoading:z||_}):null),q&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ps,{error:q,errorSql:W||d.sql||d.python,onDebugWithAssistant:le,showFeedbackButton:!1})})]})]}))]})}function _r(){const s=t.useEditorStore(r=>r.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function qr(){var d,i,x,h,v,f,m,g;const s=t.useEditorStore(y=>y.card),a=t.useEditorStore(y=>y.actions.setCard),r=t.useEditorStore(y=>y.actions.setRunSql),l=t.useEditorStore(y=>y.actions.setCardPreferences),u=t.useEditorStore(y=>y.actions.updateCardInFrame),c=C.useMemo(()=>{var y,b;return n.getTablePageSizeOptions((b=(y=s.preferences)==null?void 0:y.tablePrefs)==null?void 0:b.pageSize)},[(i=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:i.pageSize]),o=n.resolveTablePageSize((h=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:h.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"dev-pagination",checked:((f=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:y=>{var b;l({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:y}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(o),onValueChange:y=>{var A,B,S;const b=Number(y),w={...s,preferences:{...s.preferences,tablePrefs:{...(A=s.preferences)==null?void 0:A.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(w),u(w),s.sql&&((S=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&S.enableDevModePagination)&&r(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(y=>e.jsx(t.SelectItem,{value:String(y),children:y},y))})]})]})}function $e({value:s,onCommit:a,type:r="text",placeholder:l,className:u}){const[c,o]=C.useState(s),d=C.useRef(!1);C.useEffect(()=>{o(s)},[s]);const i=()=>{if(d.current){d.current=!1;return}c!==s&&a(c)},x=h=>{if(h.key==="Enter"){h.currentTarget.blur();return}h.key==="Escape"&&(d.current=!0,o(s),h.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:l,value:c,onChange:h=>o(h.target.value),onBlur:i,onKeyDown:x,className:u})}function at({defaultValue:s,label:a,options:r,value:l,onValueChange:u,className:c,icon:o,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:l,onValueChange:u,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(i=>e.jsx(t.SelectItem,{value:i.value,children:i.label},i.value))]})})]})}function $r(s,a){return n.getSlotDefinitionForIndex(s,a)||null}function Tt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,l,u]=a;return`Tabs ${Number(l)+1}-${Number(u)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function Kr(s){return s?Array.isArray(s)?s:[s]:[]}function ls(s){var l,u;if(!s)return!1;if(s.type==="text")return!!((l=s.description)!=null&&l.trim());const a=!!((u=s.sql)!=null&&u.trim()),r=t.hasValidCardConfig(s.config);return a||r}function Gr({slots:s,cards:a,minInputs:r}){const l=[],u=a.filter(Boolean).length;return r&&u<r&&l.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const i=a[c.position];ls(i)||l.push({type:"missing-required",message:`${Tt(c.position)} ("${c.label}") is required but has no data configured.`});return}const o=c.position.match(/^(\d+)-(\d+)$/);if(o){const[,i,x]=o.map(Number);for(let h=i;h<=x;h+=1){const v=a[h];if(!ls(v)){l.push({type:"missing-required",message:`${Tt(h)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const i=Number(d[1]);if(a.length<=i){l.push({type:"missing-required",message:`${Tt(i)} ("${c.label}") is required but has no data configured.`});return}for(let x=i;x<a.length;x+=1){const h=a[x];if(!ls(h)){l.push({type:"missing-required",message:`${Tt(x)} ("${c.label}") is required but has no data configured.`});break}}}}),a.forEach((c,o)=>{if(!c)return;const d=$r(s,o);if(!d||!d.expectedType)return;const i=Kr(d.expectedType);i.length!==0&&(i.includes(c.type)||l.push({type:"wrong-type",message:`${Tt(o)} ("${d.label}") expects ${i.join(", ")}, but is configured as ${c.type}.`}))})),l}const Ur={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Wn(){var D,L,R;const s=t.useEditorStore(p=>p.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],l=t.useEditorStore(p=>p.card),u=t.useEditorStore(p=>p.frame),{setCustomCardPreferences:c}=t.useEditorActions(),o=C.useMemo(()=>n.findCustomVisualConfigCard(u,l),[u,l]),d=o==null?void 0:o.customCardPreferences,{components:i,manifest:x}=n.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),h=(D=x==null?void 0:x.visuals)==null?void 0:D.find(p=>p.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),f=n.resolveMultiInputType(o||l,h)==="multiple",m=!!o&&o.id===l.id,g=(h==null?void 0:h.minInputs)??((L=o==null?void 0:o.customCardPreferences)==null?void 0:L.minInputs),y=(h==null?void 0:h.maxInputs)??((R=o==null?void 0:o.customCardPreferences)==null?void 0:R.maxInputs),b=C.useMemo(()=>n.getCustomVisualInputCards({frame:u,configCard:o||l,isMultiInputVisual:f}),[u,o,l,f]),w=C.useMemo(()=>n.buildSlotOrderedCards(b),[b]),A=C.useMemo(()=>w.map((p,F)=>{if(!p)return null;const k=n.getSlotIndexForCard(p,F),P=n.getEffectiveCardTypeForSlot(p,k,h==null?void 0:h.slots);return{...p,type:P??p.type}}),[w,h==null?void 0:h.slots]),B=C.useMemo(()=>Gr({slots:h==null?void 0:h.slots,cards:A,minInputs:g}),[h==null?void 0:h.slots,A,g]),S=C.useMemo(()=>{const p=b.findIndex(F=>(F==null?void 0:F.id)===l.id);return p<0?-1:n.getSlotIndexForCard(l,p)},[b,l]);function E(p){if(typeof p=="number")return`Tab ${p+1}`;const F=p.match(/^(\d+)-(\d+)$/);if(F){const[,P,V]=F;return`Tabs ${Number(P)+1}-${Number(V)+1}`}const k=p.match(/^(\d+)\+$/);return k?`Tabs ${Number(k[1])+1}+`:`Tab ${p}`}function I(p){return p?(Array.isArray(p)?p:[p]).join(", "):null}function T(p,F,k=[],P="",V,z,_){const q=N({key:F,defaultValue:P,settingsValue:z,sourceCard:_});return p==="input"?e.jsx($e,{className:`h-8 w-full ${t.removeRing}`,value:String(q??""),onCommit:W=>{M({key:F,value:W,settingsField:V,settingsValue:z,sourceCard:_})}},F):p==="select"?e.jsx(at,{className:"h-8 w-full",label:"",options:k,value:String(q!==void 0?q:P??""),onValueChange:W=>{M({key:F,value:W,settingsField:V,settingsValue:z,sourceCard:_})}}):null}function N({key:p,defaultValue:F,settingsValue:k,sourceCard:P}){const V=k==null?void 0:k[p];return V!==void 0?V:p==="title"&&(P==null?void 0:P.title)!==void 0?P.title:p==="description"&&(P==null?void 0:P.description)!==void 0?P.description:F}function M({key:p,value:F,settingsField:k,settingsValue:P,sourceCard:V}){const z={...P||{}},_=p==="title"&&(V==null?void 0:V.title)!==void 0,q=p==="description"&&(V==null?void 0:V.description)!==void 0;_&&F===String((V==null?void 0:V.title)??"")||q&&F===String((V==null?void 0:V.description)??"")?delete z[p]:z[p]=F,c({...s||{},[k]:z})}function j({settingsSchema:p,settingsField:F,settingsValue:k,sourceCard:P,headerLabel:V}){const z=Object.entries(p||{});return e.jsxs("div",{className:"space-y-3",children:[V&&e.jsx(t.Label,{children:V}),z.map(([_,q])=>{var W;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:q.title}),((W=q.docs)==null?void 0:W.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:q.docs.description})})]})})]}),T(q.ui,_,q.options,q.defaultValue,F,k,P)]},_)})]})}function O(){return e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:h!=null&&h.slots&&h.slots.length>0?e.jsx("div",{className:"space-y-3",children:h.slots.map((p,F)=>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:E(p.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:p.label})]}),p.description&&e.jsx("p",{className:"text-muted-foreground",children:p.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[I(p.expectedType)&&e.jsxs("span",{children:["Expected: ",I(p.expectedType)]}),p.required&&e.jsx("span",{children:"Required"})]})]},`${p.label}-${F}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||y)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&y?" • ":"",y?`Max ${y} tabs`:""]})]})})]}),f&&B.length>0&&e.jsx(n.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(n.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((p,F)=>e.jsx("li",{children:p.message},`${p.type}-${F}`))})})}),h&&!f&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l})})}),h&&f&&(h.settings||h.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&h.settings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||l,headerLabel:"Global Settings"})}),h.slotSettings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:h.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:l,headerLabel:(()=>{const p=l.tabTitle||l.title,F=S>=0?S:0,k=m?"Slot 0":`Slot ${F}`;return p?`${k}: ${p} Settings`:`${k} Settings`})()})})]})]})}return e.jsxs(n.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(n.AccordionItem,{value:"plugin-settings",children:[e.jsx(n.AccordionTrigger,{children:"Plugin"}),e.jsx(n.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!f||m)&&e.jsx(at,{icon:e.jsx(Mn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(d==null?void 0:d.url)||"",onValueChange:p=>c({...s||{url:"",componentName:""},url:p})}),f&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!f||m)&&e.jsx(e.Fragment,{children:i&&e.jsx(at,{icon:e.jsx(Sa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.map(p=>({value:p.name,label:p.name})))||[],value:s.componentName||"",onValueChange:p=>{var P;const F=(P=x==null?void 0:x.visuals)==null?void 0:P.find(V=>V.name===p),k=i==null?void 0:i.find(V=>V.name===p);c({...s,componentName:p,visualType:(F==null?void 0:F.visualType)||(k==null?void 0:k.type)||"single",minInputs:F==null?void 0:F.minInputs,maxInputs:F==null?void 0:F.maxInputs,pluginChartType:F==null?void 0:F.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(n.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(h==null?void 0:h.name)||"Settings"}),(h==null?void 0:h.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(n.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[h.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h.docs.description}),h.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(n.Markdown,{remarkPlugins:[n.remarkGfm],components:Ur,children:h.docs.dataSchema})})]}),(()=>{var F;const p=(F=h.docs)==null?void 0:F.useCases;return!p||p.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:p.map((k,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:k})]},P))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:O()})]})]})}function Hr({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function l(o,d,i){const x=[...s];x[o]={...x[o],[d]:i},a(x)}function u(o){const d=[...s];d.splice(o,1),a(d)}function c(){a([...s,r])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(n.Plus,{className:"size-3"})})]}),s.map((o,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:i=>l(d,"start",i.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:i=>l(d,"end",i.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:i=>l(d,"color",i.target.value),value:o.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>u(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Qr(){var h,v,f,m,g;const s=t.useEditorStore(y=>y.card.preferences),a=t.useEditorStore(y=>y.actions.setCardPreferences),r=t.useEditorStore(y=>y.card),l=t.hasValidCardConfig(r.config),u=t.useEditorStore(y=>y.actions.setNumberFormat);t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.decimalPlaces});const c=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.locale}),o=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.currency});t.useEditorStore(y=>y.actions.setFilterOnClickField);const d=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.colorRanges})||[],i=t.useEditorStore(y=>y.actions.setColorRanges),x=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(y=>y.currency))];return e.jsxs("div",{children:[!l&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{checked:!!((h=s==null?void 0:s.formatNumber)!=null&&h.enabled),onCheckedChange:y=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:y}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((v=s==null?void 0:s.formatNumber)==null?void 0:v.enabled)===!0||l)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:c||"none",onValueChange:y=>{var b,w,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",y,((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(y=>e.jsx(t.SelectItem,{value:y.locale,children:y.locale},y.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:y=>{var b,w,A;console.log("currency",y),u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,y==="none"?"":y,((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),x.map(y=>e.jsx(t.SelectItem,{value:y,children:y},y))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:y=>{var b,w,A;return u(Number(y),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(y=>e.jsx(t.SelectItem,{value:y,children:y},y))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:y=>{var b,w,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.locale)||"",y.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Hr,{colorRanges:d,setColorRanges:i})]})]})}const Wr={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 Jn(s){return Wr[s]}function Jr({chartType:s,showDocsLink:a=!0}){const r=Jn(s);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:r.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:r.fields.map((l,u)=>e.jsxs("tr",{className:u<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[l.name,l.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:l.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:l.description||"—"})]},l.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:r.description}),a&&r.docsUrl&&e.jsxs("a",{href:r.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:l=>l.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(n.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Yr({chartType:s}){return Jn(s)?e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(n.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Jr,{chartType:s})})]}):null}function Kt({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:a}),e.jsx(Yr,{chartType:s})]})}function Xr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Kt,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Qr,{})})]})}function bn({children:s,summary:a,open:r,className:l}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",l),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function Yn(){const[s,a]=C.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:l,setCardPreferences:u}=t.useEditorStore(x=>x.actions),c=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var h;return(h=x.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),C.useEffect(()=>{c&&a(new Array(c.length).fill(!1))},[c]);function o(x,h){var v,f;h?r!=null&&r.onClickFilter&&((v=r==null?void 0:r.onClickFilter)==null?void 0:v.length)>0?u({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):u({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(u({...r,onClickFilter:(f=r==null?void 0:r.onClickFilter)==null?void 0:f.filter(m=>m.columnIndex!==x)}),a(m=>{const g=[...m];return g[x]=!1,g}))}function d(x,h){var f;const v=(f=r==null?void 0:r.onClickFilter)==null?void 0:f.map(m=>m.columnIndex===x?{...m,expression:h.target.value}:m);u({...r,onClickFilter:v})}function i(x){var h,v,f,m;if(s!=null&&s[x]||(v=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===x))!=null&&v.expression)return e.jsx(t.Input,{value:(m=(f=r==null?void 0:r.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===x))==null?void 0:m.expression,onChange:g=>d(x,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:c==null?void 0:c.map((x,h)=>{var v,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(n.Checkbox,{checked:!!((v=r==null?void 0:r.onClickFilter)!=null&&v.find(m=>m.columnIndex===h)),onCheckedChange:m=>o(h,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((f=r==null?void 0:r.onClickFilter)==null?void 0:f.find(m=>m.columnIndex===h))&&e.jsx(n.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[h]=!m[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),i(h)]})},x)})})}const Zr=[{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"}],el=["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"],tl=el.map(s=>({label:s,value:s}));function sl(){var i,x,h,v,f,m,g,y,b,w,A,B,S,E,I,T,N,M;const s=t.useEditorStore(j=>j.card),a=(x=(i=s==null?void 0:s.preferences)==null?void 0:i.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,l]=C.useState(((v=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:v.customTopoJsonUrl)||""),{setCardPreferences:u}=t.useEditorActions(),{data:c}=n.useTopoJson(s),o=Object.keys((c==null?void 0:c.objects)||{}).map(j=>({label:j,value:j}))||[],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(Kt,{chartType:"map"}),e.jsx(bn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(at,{className:"h-9",options:d,onValueChange:j=>{console.log("value",j),u({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:j=>{l(j.target.value)},onBlur:()=>{var j;console.log("onBlur",r),u({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.mapVisualOptions,customTopoJsonUrl:r}})},value:r,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(at,{className:"h-9",options:o,value:((m=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,objectKey:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(at,{className:"h-9",options:Zr,value:((y=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projection)||"",label:"Projection",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projection:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(at,{className:"h-9",options:tl,value:((w=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(bn,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((B=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionScale:Number(j.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=(E=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:I[0])||0,onChange:j=>{var O,D,L,R;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[Number(j.target.value),((R=(L=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(N=(T=s.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:M[1])||0,onChange:j=>{var O,D,L,R;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[((R=(L=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[0])||0,Number(j.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Yn,{})]})}function Xn({color:s,onColorChange:a,onClose:r}){const[l,u]=C.useState(0),[c,o]=C.useState(100),[d,i]=C.useState(50),[x,h]=C.useState(s);C.useEffect(()=>{const b=jn(s);if(b){const w=vn(b.r,b.g,b.b);u(w.h),o(w.s),i(w.l),h(s)}},[s]);const v=b=>{u(b),m(b,c,d)},f=b=>{const w=b.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(b.clientX-w.left)/w.width)),B=Math.max(0,Math.min(1,(b.clientY-w.top)/w.height)),S=A*100,E=(1-B)*100;o(S),i(E),m(l,S,E)},m=(b,w,A)=>{const B=al(b,w,A),S=nl(B.r,B.g,B.b);h(S)},g=b=>{if(h(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const w=jn(b);if(w){const A=vn(w.r,w.g,w.b);u(A.h),o(A.s),i(A.l)}}},y=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(a(x),r())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${l}, 100%, 50%)`},onClick:f,onMouseMove:b=>{b.buttons===1&&f(b)},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:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:l,onChange:b=>v(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:x,onChange:b=>g(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:x}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(t.Button,{onClick:y,children:"OK"})]})]})}function jn(s){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function nl(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function vn(s,a,r){s/=255,a/=255,r/=255;const l=Math.max(s,a,r),u=Math.min(s,a,r);let c=0,o=0;const d=(l+u)/2;if(l!==u){const i=l-u;switch(o=d>.5?i/(2-l-u):i/(l+u),l){case s:c=((a-r)/i+(a<r?6:0))/6;break;case a:c=((r-s)/i+2)/6;break;case r:c=((s-a)/i+4)/6;break}}return{h:Math.round(c*360),s:Math.round(o*100),l:Math.round(d*100)}}function al(s,a,r){s/=360,a/=100,r/=100;let l,u,c;if(a===0)l=u=c=r;else{const o=(x,h,v)=>(v<0&&(v+=1),v>1&&(v-=1),v<.16666666666666666?x+(h-x)*6*v:v<.5?h:v<.6666666666666666?x+(h-x)*(.6666666666666666-v)*6:x),d=r<.5?r*(1+a):r+a-r*a,i=2*r-d;l=o(i,d,s+1/3),u=o(i,d,s),c=o(i,d,s-1/3)}return{r:Math.round(l*255),g:Math.round(u*255),b:Math.round(c*255)}}const yn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],rl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function rt({value:s,onChange:a,label:r}){const[l,u]=C.useState(!1),[c,o]=C.useState(!1),d=()=>{const i=yn.find(x=>x.value===s);return i?i.color:s.startsWith("#")?s:yn[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:l,onOpenChange:u,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 ${r}`})}),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:rl.map(i=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===i?"border-gray-900":"border-transparent"),style:{backgroundColor:i},onClick:()=>{a(i),u(!1)},children:e.jsx("span",{className:"sr-only",children:i})},i))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),u(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),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(Xn,{color:d(),onColorChange:i=>{a(i),o(!1)},onClose:()=>o(!1)})})]})]})}function _t(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Nn(s,a){if(!a||a==="auto")return{type:"auto"};const r={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?xs(r,_t(a)):r}function xs(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const ll=["auto","number","currency","percent","scientific","date"],ol=[{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"}],il=[{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"}],cl=s=>s.charAt(0).toUpperCase()+s.slice(1);function vt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=s.type||"auto",c=u==="auto"?s:Nn(s,u),o=m=>{m.stopPropagation()},d=(m,g)=>{a({...c,[m]:g})},[i,x]=C.useState(()=>String(c.decimalPlaces??_t(u))),[h,v]=C.useState(()=>c.multiplyBy!==void 0?String(c.multiplyBy):""),f=m=>{a(Nn(s,m))};return C.useEffect(()=>{x(String(c.decimalPlaces??_t(u)))},[c.decimalPlaces,u]),C.useEffect(()=>{v(c.multiplyBy!==void 0?String(c.multiplyBy):"")},[c.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:l}),e.jsxs(t.Select,{value:u,onValueChange:m=>f(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ll.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":cl(m)},m))})]})]}),u!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(u)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:i,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");x(g),g!==""&&a(xs(c,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(i!=="")return;const m=_t(u);x(String(m)),a(xs(c,m))},className:"h-8 text-xs"})})]}),u==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ol.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(u)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:il.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(u)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("negativeInParentheses",m)})]}),u==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:h,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");v(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),u==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function js({value:s,onChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=t.toTFormatOptions(t.fromSemanticFormat(s))||{},c=o=>{a(t.fromTFormatOptions(o))};return e.jsx(vt,{formatOptions:u,onFormatOptionsChange:c,showTitle:r,title:l})}function dl(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:r}=t.useEditorActions(),{dashboardFilterableFields:l}=n.useFilterableFields(),{assignFilter:u}=n.useAssignFilter();function c(d){const i=u(d,"frame");r({...a,filterId:i})}const o=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(ul,{onSelect:c,columns:l}),o&&e.jsx(n.FilterHeader,{filter:o})]})}function ul({columns:s,onSelect:a}){var d;const[r,l]=zt.useState(!1),[u,c]=zt.useState(""),o=zt.useCallback(i=>[i.label,i.name,i.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:r,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":r,className:"w-full justify-between font-normal",children:[u?((d=s.find(i=>i.id===u))==null?void 0:d.label)||u:"Select Column...",e.jsx(n.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No column found."}),e.jsx(n.CommandGroup,{children:s==null?void 0:s.map(i=>e.jsxs(n.CommandItem,{value:o(i),onSelect:()=>{const x=i.id===u?"":i.id;c(x),l(!1),x&&a(i)},children:[i.label||i.name,e.jsx(n.CheckIcon,{className:t.cn("ml-auto h-4 w-4",u===i.id?"opacity-100":"opacity-0")})]},i.id))})]})]})})]})}const ml=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],xl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function hl({cardType:s="table"}){var h,v,f,m,g;const a=t.useEditorStore(y=>y.card),r=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.preferences}),l=t.useEditorStore(y=>y.actions.setCardPreferences),u=((h=a.config)==null?void 0:h.metricColumns)||[],c=u.some(y=>y.comparisonType&&y.comparisonType!=="none"),o=((v=r==null?void 0:r.tableVisualOptions)==null?void 0:v.metricComparison)||{},d=y=>{l({...r,tableVisualOptions:{...r==null?void 0:r.tableVisualOptions,metricComparison:{...o,...y}}})},i={increase:((f=o.colors)==null?void 0:f.increase)||"green",decrease:((m=o.colors)==null?void 0:m.decrease)||"red",neutral:((g=o.colors)==null?void 0:g.neutral)||"neutral"},x=y=>{l({...r,allowDownload:y})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(n.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.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(Fn,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:o.calculatedAs||"change_difference",onValueChange:y=>d({calculatedAs:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ml.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(vt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:y=>d({formatOptions:y}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:y=>d({indicatorStyle:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xl.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(rt,{value:i.increase,onChange:y=>d({colors:{...i,increase:y}}),label:"Increase"}),e.jsx(rt,{value:i.decrease,onChange:y=>d({colors:{...i,decrease:y}}),label:"Decrease"}),e.jsx(rt,{value:i.neutral,onChange:y=>d({colors:{...i,neutral:y}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(n.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:y=>d({lowerIsBetter:!!y})})]})]})]}),u.length>0&&e.jsxs(n.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:u.map(y=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:y.label||y.name}),e.jsx(js,{value:y.format,onChange:b=>{var A;const w=(((A=a.config)==null?void 0:A.metricColumns)||[]).map(B=>B.id===y.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:w})},showTitle:!1})]},y.id))})]}),e.jsxs(n.AccordionItem,{value:"item-3",children:[e.jsx(n.AccordionTrigger,{children:"Click Filters"}),e.jsxs(n.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Yn,{}),e.jsx(dl,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.Checkbox,{onCheckedChange:x,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 pl(){var l;const s=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:a}=t.useEditorStore(u=>u.actions);function r(u){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:u==="dynamic"}})}return e.jsxs(n.RadioGroup,{value:(l=s==null?void 0:s.textVisualOptions)!=null&&l.isDynamicText?"dynamic":"static",onValueChange:r,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function fl(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Kt,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(pl,{})]})]})}const gl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function bl(){var E,I,T,N,M,j,O,D,L,R;const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var F;return(F=p.card)==null?void 0:F.preferences}),r=Me.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions(),c=C.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:o}=n.useEditorCardQuery(c),[d,i]=C.useState({}),[x,h]=C.useState(null),[v,f]=C.useState(null),m=C.useMemo(()=>{var P,V,z,_,q,W,$;if(!(o!=null&&o.records)||o.records.length===0)return[];const p=r==="stackedBar"||r==="stackedLine",F=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",k=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((p||F)&&k){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const U=new Set;return o.pivotSchema.forEach(se=>{se.alias&&U.add(se.alias)}),Array.from(U)}if(o.records.length>0){const U=o.records[0],se=Object.keys(U),ie=new Set;(V=s==null?void 0:s.config)!=null&&V.groupByColumns&&s.config.groupByColumns.forEach(me=>{ie.add(me.label||me.name),ie.add(me.alias||me.name)});const le=new Set;return(z=s==null?void 0:s.config)!=null&&z.metricColumns&&s.config.metricColumns.forEach(me=>{const ue=me.alias||me.name;le.add(ue),le.add(`${ue}_count`),le.add(`${ue}_sum`),le.add(`${ue}_avg`),le.add(`${ue}_min`),le.add(`${ue}_max`);const Ne=me.entityName||me.qualifiedEntityName;Ne&&(le.add(`${Ne}_${ue}`),le.add(`${Ne}_${ue}_count`))}),se.filter(me=>!ie.has(me)&&!le.has(me))}}if((F||p)&&!k&&((q=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&q.length))return s.config.metricColumns.map(U=>U.alias||U.label||U.name);if(($=(W=s==null?void 0:s.config)==null?void 0:W.groupByColumns)!=null&&$.length){const U=s.config.groupByColumns[0],se=U.label||U.name,ie=new Set;return o.records.forEach(le=>{const de=le[se];de!=null&&ie.add(String(de))}),Array.from(ie)}return[]},[o,(E=s==null?void 0:s.config)==null?void 0:E.groupByColumns,(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns,(T=s==null?void 0:s.config)==null?void 0:T.metricColumns,r]),g=C.useMemo(()=>n.getDefaultChartColors(),[]);C.useEffect(()=>{const p={};m.forEach((F,k)=>{p[F]=n.getColorForValue(F,k,a==null?void 0:a.colorConfig)}),i(p)},[m,a==null?void 0:a.colorConfig,g]);const y=(p,F)=>{const k={...d,[p]:F};i(k);const P={...a||{},colorConfig:{segments:k}};l(P);const V={...s,preferences:P};u(V)},b=(p,F)=>{var q;const k=g[F%g.length],{[p]:P,...V}=((q=a==null?void 0:a.colorConfig)==null?void 0:q.segments)||{},z={...a||{},colorConfig:{segments:V}};l(z);const _={...s,preferences:z};u(_),i(W=>({...W,[p]:k}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((M=(N=s==null?void 0:s.config)==null?void 0:N.groupByColumns)==null?void 0:M.length)||((O=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:O.length):(L=(D=s==null?void 0:s.config)==null?void 0:D.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const B=()=>{const p={...a||{},colorConfig:{segments:{}}};l(p);const F={...s,preferences:p};u(F);const k={};m.forEach((P,V)=>{k[P]=n.getColorForValue(P,V,void 0)}),i(k)},S=Object.keys(((R=a==null?void 0:a.colorConfig)==null?void 0:R.segments)||{}).length>0;return e.jsxs(n.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ja.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(n.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:S&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(ms.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((p,F)=>{const k=n.isDefaultColor(d[p],F),P=!k;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===p,onOpenChange:V=>h(V?p: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[p]}})}),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((V,z)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[p]===V?"border-gray-900":"border-transparent"),style:{backgroundColor:V},onClick:()=>{y(p,V),h(null)},children:[z===F%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:V})]},`default-${z}`))})]}),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:gl.map((V,z)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[p]===V?"border-2 border-gray-900":V==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:V},onClick:()=>{y(p,V),h(null)},children:e.jsx("span",{className:"sr-only",children:V})},`preset-${z}`))})]}),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:()=>{f({value:p,color:d[p]}),h(null)},children:"Custom color"}),!k&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(p,F),h(null)},children:[e.jsx(ms.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:p}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},p)})}),v&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>f(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Xn,{color:v.color,onColorChange:p=>{y(v.value,p),f(null)},onClose:()=>f(null)})})]})]})})]})}function Ye({value:s,onSave:a,placeholder:r="",type:l="text",className:u=""}){const[c,o]=C.useState(s??""),[d,i]=C.useState(!1);C.useEffect(()=>{o(s??"")},[s]);const x=()=>{a(c),i(!1)},h=()=>{o(s??""),i(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${u}`,children:[e.jsx(t.Input,{placeholder:r,type:l,value:d?c:s??"",onChange:v=>{o(v.target.value),i(!0)},onFocus:()=>i(!0),onClick:v=>v.stopPropagation(),className:"h-8 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.stopPropagation(),v.key==="Enter"&&d&&c!==s?x():v.key==="Escape"&&h()},"aria-label":r||"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:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function os({axis:s,label:a,type:r,config:l,onChange:u,defaultTitle:c,hidePosition:o}){var g,y,b,w,A,B,S,E,I,T,N,M,j,O;const d=n.normalizeContextFormatMode({formatMode:l==null?void 0:l.formatMode,formatOptions:l==null?void 0:l.formatOptions}),i=(D,L)=>{u({...l??{},[D]:L})},x=(D,L)=>{var k,P,V,z;const R=D==="enabled"&&L===!0,p=(k=l==null?void 0:l.name)==null?void 0:k.text,F=R&&!p&&c;u({...l??{},name:{...l==null?void 0:l.name,enabled:D==="enabled"?L:((P=l==null?void 0:l.name)==null?void 0:P.enabled)??!1,text:D==="text"?L:F?c:p,fontSize:D==="fontSize"?L:(V=l==null?void 0:l.name)==null?void 0:V.fontSize,fontWeight:D==="fontWeight"?L:(z=l==null?void 0:l.name)==null?void 0:z.fontWeight}})},h=(D,L)=>{var R,p;u({...l??{},labels:{enabled:D==="enabled"?L:((R=l==null?void 0:l.labels)==null?void 0:R.enabled)??!0,rotation:D==="rotation"?L:(p=l==null?void 0:l.labels)==null?void 0:p.rotation}})},v=(D,L)=>{u({...l??{},scale:{...l==null?void 0:l.scale,[D]:L===""?"auto":Number(L)}})},f=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(n.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(n.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-[12px] font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(t.Switch,{size:"sm",checked:(l==null?void 0:l.enabled)!==!1,onCheckedChange:D=>i("enabled",D),onClick:D=>D.stopPropagation()})]}),e.jsxs(n.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:`${s}-title-enabled`,checked:((g=l==null?void 0:l.name)==null?void 0:g.enabled)??!1,onCheckedChange:D=>x("enabled",D===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((y=l==null?void 0:l.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Ye,{placeholder:`${a} title`,value:((b=l==null?void 0:l.name)==null?void 0:b.text)||"",onSave:D=>x("text",D),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(Ye,{type:"number",placeholder:"12",value:String(((w=l==null?void 0:l.name)==null?void 0:w.fontSize)||12),onSave:D=>x("fontSize",Number(D)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((A=l==null?void 0:l.name)==null?void 0:A.fontWeight)||"normal",onValueChange:D=>x("fontWeight",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(l==null?void 0:l.position)||"auto",onValueChange:D=>i("position",D),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:f.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"?"Auto (Default)":t.titleCase(D)},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",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((B=l==null?void 0:l.labels)==null?void 0:B.enabled)!==!1,onCheckedChange:D=>h("enabled",D)})]}),((S=l==null?void 0:l.labels)==null?void 0:S.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(((E=l==null?void 0:l.labels)==null?void 0:E.rotation)||"auto"),onValueChange:D=>h("rotation",D==="auto"?"auto":Number(D)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"?"Auto (Default)":`${D}°`},D))})]})]})]}),r==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:d==="override",onCheckedChange:D=>u({...l,formatMode:D?"override":"inherit"})})]}),d==="override"&&e.jsx(vt,{formatOptions:(l==null?void 0:l.formatOptions)||{},onFormatOptionsChange:D=>u({...l,formatMode:"override",formatOptions:D}),showTitle:!1})]}),r==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{type:"number",placeholder:"auto",value:((I=l==null?void 0:l.scale)==null?void 0:I.min)==="auto"||((T=l==null?void 0:l.scale)==null?void 0:T.min)===void 0?"":String(l.scale.min),onSave:D=>v("min",D),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(Ye,{type:"number",placeholder:"auto",value:((N=l==null?void 0:l.scale)==null?void 0:N.max)==="auto"||((M=l==null?void 0:l.scale)==null?void 0:M.max)===void 0?"":String(l.scale.max),onSave:D=>v("max",D),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(Ye,{type:"number",placeholder:"auto",value:((j=l==null?void 0:l.scale)==null?void 0:j.stepSize)==="auto"||((O=l==null?void 0:l.scale)==null?void 0:O.stepSize)===void 0?"":String(l.scale.stepSize),onSave:D=>v("stepSize",D),className:""})})]})]})]})]})]})}function is(s,a,r){var c,o,d;if(s==="x"){const i=(o=(c=a==null?void 0:a.config)==null?void 0:c.groupByColumns)==null?void 0:o[0];return(i==null?void 0:i.label)||(i==null?void 0:i.name)||""}const l=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],u=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const i=l.filter((x,h)=>{const v=u.find(f=>f.idx===h);return!v||v.yAxisId!=="y2"});return i.length===1&&(i[0].label||i[0].name)||""}if(s==="y2"){const i=l.filter((x,h)=>{const v=u.find(f=>f.idx===h);return(v==null?void 0:v.yAxisId)==="y2"});return i.length===1&&(i[0].label||i[0].name)||""}return""}function jl(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:l}=t.useEditorActions(),u=Me.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(u))return null;const c=n.AxisConfigurator.getAxisInfo(u,a);if(!c.hasXAxis&&!c.hasYAxis)return null;const o=(i,x)=>{let h;i==="x"?h="xAxisConfig":i==="y"?h="yAxisConfig":h="secondaryYAxisConfig";const v={...a||{},[h]:x};r(v);const f={...s,preferences:v};l(f)},d=c.hasY2Axis&&u==="combo";return e.jsxs(n.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs(n.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[c.hasXAxis&&e.jsx(os,{axis:"x",label:"X-Axis",type:c.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>o("x",i),defaultTitle:is("x",s,a)}),c.hasYAxis&&e.jsx(os,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>o("y",i),defaultTitle:is("y",s,a)}),d&&e.jsx(os,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:i=>o("y2",i),defaultTitle:is("y2",s,a),hidePosition:!0})]})})]})}function vl(){const s=t.useEditorStore(v=>v.card),a=Me.useEffectiveEditorCardType(),r=t.useEditorStore(v=>{var f,m,g,y;return(y=(g=(m=(f=v.card)==null?void 0:f.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:y.legend}),{setLegendOptions:l}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const u=n.getDefaultLegendConfig(a),c=(u==null?void 0:u.display)??!0,o=(u==null?void 0:u.position)??"top",d=(u==null?void 0:u.align)??"center",i=(v,f)=>{const m={...r,[v]:f};l(m)},x=["top","bottom","left","right"],h=["start","center","end"];return e.jsxs(n.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.display)??c,onCheckedChange:v=>i("display",v)})]}),((r==null?void 0:r.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:(r==null?void 0:r.position)||o,onValueChange:v=>i("position",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(r==null?void 0:r.align)||d,onValueChange:v=>i("align",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]})]})]})})]})}function yl(){var L,R,p,F,k,P,V;const s=t.useEditorStore(z=>z.card),a=Me.useEffectiveEditorCardType(),r=t.useEditorStore(z=>{var _,q;return(q=(_=z.card)==null?void 0:_.preferences)==null?void 0:q.dataLabelsConfig}),l=t.useEditorStore(z=>{var _;return(_=z.card)==null?void 0:_.preferences}),{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const o=a==="bullet"?((L=l==null?void 0:l.bulletConfig)==null?void 0:L.orientation)??(((R=l==null?void 0:l.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((p=l==null?void 0:l.chartOptions)==null?void 0:p.indexAxis)==="y",i=a==="stackedBar"||a==="stackedLine",x=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",h=a==="bubble"||a==="scatter",v=(k=(F=l==null?void 0:l.chartOptions)==null?void 0:F.plugins)==null?void 0:k.datalabels,f=(v==null?void 0:v.display)!==!1&&((v==null?void 0:v.anchor)||(v==null?void 0:v.align)),m=n.getDefaultDataLabelsConfig(a,s.preferences),g=r??m,y=(m==null?void 0:m.enabled)??f??!1,b=(r==null?void 0:r.enabled)!==void 0?r.enabled:y,w=(z,_)=>{const $={...m??{},...r??{},[z]:_};z==="enabled"&&($.display=_,_&&h&&!$.position&&($.position="bottom")),z==="position"&&h&&($.position="bottom"),z==="formatMode"&&_==="inherit"&&($.format=void 0,$.formatOptions=void 0);const U={...s.preferences||{},dataLabelsConfig:$};u(U);const se={...s,preferences:U};c(se)},A=(z,_)=>{const q=r??{},$={...m??{},...q,font:{...q.font||{},[z]:_}},U={...s.preferences||{},dataLabelsConfig:$};u(U);const se={...s,preferences:U};c(se)},B=()=>{const z=a;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":d?"right":"top"},S=a!=="treemap"&&a!=="heatmap",E=a!=="treemap",I=B();let T=[];if(S)if(h)T=["bottom"];else if(i||x)T=["center"];else{const z=d?["center","left","right"]:["center","top","bottom"];T=["auto",...a==="bullet"?z:z.filter(q=>q!==I),"custom"]}const N=()=>t.titleCase(I),M=["center","start","end"],j=["center","start","end","top","bottom"],O=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),D=(g==null?void 0:g.format)==="none";return e.jsxs(n.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:b,onCheckedChange:z=>w("enabled",z)})]}),b&&e.jsxs(e.Fragment,{children:[S&&!i&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:h?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:z=>w("position",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:z==="auto"?N():z==="custom"?"Custom (Advanced)":t.titleCase(z)},z))})]})]}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.showTotal)??!1,onCheckedChange:z=>w("showTotal",z)})]}),(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:z=>w("anchor",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]}),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:z=>w("align",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:j.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:O==="override",onCheckedChange:z=>w("formatMode",z?"override":"inherit")})]}),O==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:D,onCheckedChange:z=>{const _=r??{},W={...m??{},..._,formatMode:"override",format:z?"none":void 0,formatOptions:z?void 0:_.formatOptions},$={...s.preferences||{},dataLabelsConfig:W};u($),c({...s,preferences:$})}})]}),!D&&e.jsx(vt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:z=>{const W={...m??{},...r??{},formatMode:"override",format:z.type&&z.type!=="auto"?z.type:void 0,formatOptions:z},$={...s.preferences||{},dataLabelsConfig:W};u($),c({...s,preferences:$})},showTitle:!1})]})]}),E&&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(Ye,{type:"number",placeholder:"12",value:String(((P=g==null?void 0:g.font)==null?void 0:P.size)||12),onSave:z=>A("size",Number(z)),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:((V=g==null?void 0:g.font)==null?void 0:V.weight)||"normal",onValueChange:z=>A("weight",z),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:z=>{z==="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(Ye,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:z=>w("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Cn={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
183
- Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Nl(){var f,m,g,y,b,w,A,B,S,E;const s=t.useEditorStore(I=>I.card),{setCardPreferences:a}=t.useEditorActions(),r=Me.useEffectiveEditorCardType(),l=((f=s.config)==null?void 0:f.metricColumns)||[],u=((m=s.config)==null?void 0:m.groupByColumns)||[],c=l.length===2&&u.length===0,o=l.some(I=>I.comparisonType&&I.comparisonType!=="none");if(!(r==="kpi"&&(c||o)))return null;const i=((y=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:y.metricComparison)||{},x=I=>{var N;const T={...s.preferences,kpiVisualOptions:{...(N=s.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...i,...I}}};a(T)},h=o||i.enabled,v=l.some(I=>I.comparisonType==="previous_period"||I.comparisonType==="same_period_last_year"||I.comparisonType==="start_vs_end");return e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&l.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:i.enabled||!1,onCheckedChange:I=>x({enabled:I,...I&&!i.calculationType?{calculationType:"difference"}:{}})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const I=i.calculationType||"difference",T=Cn[I];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:T==null?void 0:T.label}),e.jsx("p",{children:T==null?void 0:T.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:T==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",T==null?void 0:T.example]})]})})()})]})]}),e.jsxs(t.Select,{value:i.calculationType||"difference",onValueChange:I=>x({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(Cn).map(([I,T])=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:T.label},I))})]})]}),e.jsx(vt,{formatOptions:i.formatOptions||{},onFormatOptionsChange:I=>x({formatOptions:I}),showTitle:!0,title:"COMPARISON FORMAT"}),(v||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:i.position||"right",onValueChange:I=>x({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(n.Checkbox,{id:"show-arrow",checked:i.showArrow!==!1,onCheckedChange:I=>x({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(n.Checkbox,{id:"show-color",checked:i.showColor!==!1,onCheckedChange:I=>x({showColor:I})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),i.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(rt,{value:((b=i.colorConfig)==null?void 0:b.increase)||"green",onChange:I=>x({colorConfig:{...i.colorConfig,increase:I}}),label:"Primary > Secondary"}),e.jsx(rt,{value:((w=i.colorConfig)==null?void 0:w.decrease)||"red",onChange:I=>x({colorConfig:{...i.colorConfig,decrease:I}}),label:"Primary < Secondary"}),e.jsx(rt,{value:((A=i.colorConfig)==null?void 0:A.noChange)||"neutral",onChange:I=>x({colorConfig:{...i.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(n.Checkbox,{id:"conditional-label",checked:i.conditionalLabel||!1,onCheckedChange:I=>x({conditionalLabel:I})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),i.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((B=i.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:I=>x({conditionalLabels:{...i.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:((S=i.conditionalLabels)==null?void 0:S.decrease)??"Decrease",onChange:I=>x({conditionalLabels:{...i.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:((E=i.conditionalLabels)==null?void 0:E.noChange)??"No change",onChange:I=>x({conditionalLabels:{...i.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:i.labelName??"",onChange:I=>x({labelName:I.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Cl(){var c;const s=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),a=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const l=((c=a==null?void 0:a.chartOptions)==null?void 0:c.treemapColorMode)??"branch",u=o=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:o}};r(d)};return e.jsxs(n.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(n.RadioGroup,{value:l,onValueChange:o=>u(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const Sl=Object.keys(n.HEATMAP_PRESET_PALETTES);function wl(){const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var m;return(m=f.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),l=(s==null?void 0:s.type)==="heatmap",u=(a==null?void 0:a.heatmapConfig)||{},c=u.colorPalette??"green",o=u.legendPosition??"bottom",d=C.useMemo(()=>u.colorRange&&u.colorRange[0]&&u.colorRange[1]?[u.colorRange[0],u.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[u.colorRange]),i=f=>{const m={...u,...f};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:m})},x=f=>{i({colorPalette:f,colorRange:f==="custom"?u.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},h=(f,m)=>{const g=[...d];g[f]=m,i({colorPalette:"custom",colorRange:g})},v=f=>{i({legendPosition:f})};return l?e.jsxs(n.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(n.RadioGroup,{value:c,onValueChange:f=>x(f??"blue"),className:"space-y-3",children:[Sl.map(f=>{const m=n.HEATMAP_PRESET_PALETTES[f];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`heatmap-${f}`,value:f}),e.jsxs(t.Label,{htmlFor:`heatmap-${f}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},f)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(rt,{value:d[0],onChange:f=>h(0,f),label:"Start color"}),e.jsx(rt,{value:d[1],onChange:f=>h(1,f),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:f=>v(f??"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(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f[0].toUpperCase()+f.slice(1)},f))})]})]})]})]}):null}const Sn=["poor","satisfactory","good"];function wn(s){if(!s)return;const a={...s};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function Tl(){var L,R;const s=t.useEditorStore(p=>p.card.preferences),a=t.useEditorStore(p=>p.card),r=t.useEditorStore(p=>p.isDevMode),{setCardPreferences:l,setChartOrientation:u}=t.useEditorActions(),c=C.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,[i,x]=C.useState(c.showRanges??!1),[h,v]=C.useState(c.rangesArePercentages??!1),f=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[m,g]=C.useState(f);C.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),C.useEffect(()=>{v(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const y=c.targetValue===void 0?"":String(c.targetValue);C.useEffect(()=>{const p=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;g(p)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const b=C.useMemo(()=>{var p,F;return((F=(p=a==null?void 0:a.config)==null?void 0:p.metricColumns)==null?void 0:F.map(k=>{const P=k.label||k.name||k.alias||"";return{value:P,label:P}}))||[]},[(L=a==null?void 0:a.config)==null?void 0:L.metricColumns]);C.useEffect(()=>{var q,W;if(!s||b.length===0)return;const p={};let F=!1;const k=(q=b[1])==null?void 0:q.value;!c.targetMetricKey&&k&&(p.targetMetricKey=k,F=!0);const P=(W=b[2])==null?void 0:W.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&P&&(p.comparativeMetricKey=P,F=!0);const V=b.slice(3),z={...c.rangeKeys||{}};let _=!1;if(Sn.forEach(($,U)=>{!z[$]&&V[U]&&(z[$]=V[U].value,_=!0)}),_&&(p.rangeKeys=z,F=!0,c.showRanges===void 0&&(p.showRanges=!0)),F){const $=wn({...c,...p});l({...s,bulletConfig:$})}},[b,c,s,l]);const w=p=>{const F=wn({...c,...p});l({...s,bulletConfig:F})},A=(p,F)=>{const k={...c.rangeKeys||{},[p]:F.trim()};F.trim()||delete k[p],w({rangeKeys:Object.keys(k).length>0?k:void 0})},B=(p,F)=>{const k=F===""?void 0:Number(F),P={...c.ranges||{}};k===void 0||Number.isNaN(k)?delete P[p]:P[p]=k,w({ranges:Object.keys(P).length?P:void 0})},S=p=>{if(p===""){w({targetValue:void 0});return}const F=Number(p);w({targetValue:Number.isNaN(F)?void 0:F})},E=(p,F)=>{const k=F.trim(),P={...c.rangeLabels||{}};k?P[p]=k:delete P[p],w({rangeLabels:Object.keys(P).length>0?P:void 0})},I=p=>{x(p),w({showRanges:p})},T=p=>{v(p),w({rangesArePercentages:p})},N=c.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),M=p=>{w({orientation:p}),u(p==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(p=>({value:p.value,label:p.label}))],O=j,D=p=>{if(g(p),!p){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){w({disableAutoComparative:!1});return}if(c.comparativeMetricKey)w({disableAutoComparative:!1});else{const F=b.find(k=>k.value!==c.targetMetricKey);w({comparativeMetricKey:F==null?void 0:F.value,disableAutoComparative:!1})}};return e.jsxs(n.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:N,onValueChange:p=>M(p),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:p=>w({targetMetricKey:p==="__none"?void 0:p}),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"}),b.map(p=>e.jsx(t.SelectItem,{value:p.value,className:"text-xs",children:p.label},p.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:c.comparativeMetricKey||"__none",onValueChange:p=>w({comparativeMetricKey:p==="__none"?void 0:p,disableAutoComparative:p==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:j.map(p=>e.jsx(t.SelectItem,{value:p.value,className:"text-xs",children:p.label},p.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:p=>D(p)})]}),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($e,{type:"number",className:"h-8 text-xs",value:y,onCommit:S,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(t.Switch,{size:"sm",checked:i,onCheckedChange:I})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:h,disabled:!i,onChange:p=>T(p.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),i&&e.jsx("div",{className:"space-y-3",children:Sn.map(p=>{var F,k,P,V,z;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," LABEL"]}),e.jsx($e,{placeholder:`Display label (${p})`,value:((F=c.rangeLabels)==null?void 0:F[p])||"",onCommit:_=>E(p,_),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," COLUMN"]}),e.jsxs(t.Select,{value:((k=c.rangeKeys)==null?void 0:k[p])||"__none",onValueChange:_=>{_==="__none"?A(p,""):A(p,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:O.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:[p," COLUMN KEY"]}),e.jsx($e,{placeholder:"Column key",value:((P=c.rangeKeys)==null?void 0:P[p])||"",onCommit:_=>A(p,_),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," VALUE"]}),e.jsx($e,{type:"number",placeholder:h?"0.80":"Static value",value:((V=c.ranges)==null?void 0:V[p])===void 0?"":String((z=c.ranges)==null?void 0:z[p]),onCommit:_=>B(p,_),className:"h-8 text-xs"})]})]},p)})})]})]})]})}function Tn(s){if(!s)return;const a={...s};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function El(){var E,I,T,N,M,j,O,D,L,R,p,F;const s=t.useEditorStore(k=>k.card.preferences),a=t.useEditorStore(k=>k.card),r=Me.useEffectiveEditorCardType(),l=t.useEditorStore(k=>k.isDevMode),{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions(),o=r==="bubble",d=r==="scatter",i=C.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),h=t.hasValidCardConfig(a==null?void 0:a.config)&&!l,v=C.useMemo(()=>{var k,P;return((P=(k=a==null?void 0:a.config)==null?void 0:k.metricColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(E=a==null?void 0:a.config)==null?void 0:E.metricColumns]),f=C.useMemo(()=>{var k,P;return((P=(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.groupByColumns]),m=C.useMemo(()=>i.enableGrouping!==void 0?i.enableGrouping:!l&&f.length>=2,[i.enableGrouping,l,f.length]),[g,y]=C.useState(m);C.useEffect(()=>{y(m)},[m]);const b=k=>{const P={...s||{},bubbleScatterConfig:k};u(P),a&&c({...a,preferences:P})},w=k=>{u(k),a&&c({...a,preferences:k})};C.useEffect(()=>{if(!s||v.length===0)return;const k={};let P=!1;if(!i.xMetricKey&&v[0]&&(k.xMetricKey=v[0].value,P=!0),!i.yMetricKey&&v[1]&&(k.yMetricKey=v[1].value,P=!0),o&&!i.radiusMetricKey&&v[2]&&(k.radiusMetricKey=v[2].value,P=!0),!i.labelKey&&f[0]&&(k.labelKey=f[0].value,P=!0),m&&!i.groupKey&&f[1]&&(k.groupKey=f[1].value,k.enableGrouping=!0,P=!0),P){const V=Tn({...i,...k});b(V)}},[v,f,i,s,u,o,m]);const A=k=>{const P=Tn({...i,...k});b(P)},B=k=>{y(k),A({enableGrouping:k,groupKey:k?i.groupKey:void 0})};if(!o&&!d)return null;const S=o?n.Circle:n.ChartScatter;return e.jsxs(n.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),h?e.jsxs(t.Select,{value:i.labelKey||"",onValueChange:k=>A({labelKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for labels",value:i.labelKey||"",onCommit:k=>A({labelKey:k})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),h?e.jsxs(t.Select,{value:i.groupKey||"",onValueChange:k=>A({groupKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:i.groupKey||"",onCommit:k=>A({groupKey:k})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),h?e.jsxs(t.Select,{value:i.xMetricKey||"",onValueChange:k=>A({xMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:i.xMetricKey||"",onCommit:k=>A({xMetricKey:k})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),h?e.jsxs(t.Select,{value:i.yMetricKey||"",onValueChange:k=>A({yMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:i.yMetricKey||"",onCommit:k=>A({yMetricKey:k})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),h?e.jsxs(t.Select,{value:i.radiusMetricKey||"",onValueChange:k=>A({radiusMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for radius",value:i.radiusMetricKey||"",onCommit:k=>A({radiusMetricKey:k})})]})]}),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:i.radiusScale||"sqrt",onValueChange:k=>A({radiusScale:k}),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"})]})]})]}),i.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($e,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((T=i.minRadius)==null?void 0:T.toString())||"",onCommit:k=>A({minRadius:k?Number(k):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx($e,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((N=i.maxRadius)==null?void 0:N.toString())||"",onCommit:k=>A({maxRadius:k?Number(k):void 0})})]})]}),i.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",i.fixedRadius||10]}),e.jsx(n.Slider,{value:[i.fixedRadius||10],onValueChange:([k])=>A({fixedRadius:k}),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: ",i.fixedRadius||5]}),e.jsx(n.Slider,{value:[i.fixedRadius||5],onValueChange:([k])=>A({fixedRadius:k}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(t.Switch,{size:"sm",checked:((j=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:j.enabled)??!1,onCheckedChange:k=>{var z,_,q,W;const P=i.xMetricKey||"X Axis",V=i.yMetricKey||"Y Axis";w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:k,text:((_=(z=s==null?void 0:s.xAxisConfig)==null?void 0:z.name)==null?void 0:_.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:k,text:((W=(q=s==null?void 0:s.yAxisConfig)==null?void 0:q.name)==null?void 0:W.text)||V}}})}})]}),((D=(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name)==null?void 0:D.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:i.xMetricKey||"X Axis",value:((R=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:R.text)||"",onCommit:k=>{var P;w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:k||i.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:i.yMetricKey||"Y Axis",value:((F=(p=s==null?void 0:s.yAxisConfig)==null?void 0:p.name)==null?void 0:F.text)||"",onCommit:k=>{var P;w({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:k||i.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Il=[{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 kl(){const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var m;return(m=f.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),l=(s==null?void 0:s.type)==="funnel",u=(a==null?void 0:a.funnelConfig)||{},c=u.percentMode??"percentOfTotal",o=u.shrinkFraction??1,d=u.labelThreshold??0,i=f=>{const m={...u,...f};r({...a||{},funnelConfig:m})},x=f=>{i({percentMode:f})},h=f=>{i({shrinkFraction:f[0]})},v=f=>{i({labelThreshold:f[0]})};return l?e.jsxs(n.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(n.RadioGroup,{value:c,onValueChange:f=>x(f),className:"space-y-2",children:Il.map(f=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`funnel-${f.value}`,value:f.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${f.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:f.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]},f.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(n.Slider,{value:[o],onValueChange:h,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(n.Slider,{value:[d],onValueChange:v,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function Gt(){const s=t.useEditorStore(c=>c.card),{data:a}=n.useEditorCardQuery(s),{keys:r}=n.getKeys((a==null?void 0:a.records)||[]),l=r.slice(1).filter(c=>!t.METADATA_KEYS.includes(c));let u=l;if(["stackedBar","stackedLine"].includes(s.type)){const c=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:r[0],pivotKey:r[1],valueKey:r[2]}),{keys:o}=n.getKeys(c);u=o.slice(1)}return{transformedMetricKeys:u,dimensionKeys:r.slice(0,1),keys:r,defaultMetricKeys:l}}const Dl=[{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"}],Al=[{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)"}],Ml=["center","start","end"],Ll=["center","start","end","top","bottom"];function Ut({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:l=!0,positionOptions:u,showAppearance:c=!0}){var g,y,b,w,A,B;const o=u??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=l?["auto","number","currency","percent","none"]:["number","currency","percent","none"],i=(S,E)=>{const I={...s,[S]:E};a(I)},x=(S,E)=>{const I={...s,font:{...(s==null?void 0:s.font)||{},[S]:E}};a(I)},h=(S,E)=>{const I={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:E}};a(I)},v=()=>r?"Right":"Top",f=s||{},m=f.format||(l?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:f.position||"auto",onValueChange:S=>i("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?v():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),f.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:f.anchor||"center",onValueChange:S=>i("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]}),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(f.align||"center"),onValueChange:S=>i("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:S=>i("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&l?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Ye,{type:"number",placeholder:"0",value:String(((g=f.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:S=>h("decimalPlaces",Number(S)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((y=f.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:S=>h("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((b=f.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:S=>h("useSuffix",S)})]}),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=f.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:S=>h("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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(Ye,{type:"number",placeholder:"12",value:String(((A=f.font)==null?void 0:A.size)||12),onSave:S=>x("size",Number(S)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((B=f.font)==null?void 0:B.weight)||"normal",onValueChange:S=>x("weight",S),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:f.color==="auto"||!f.color?"auto":"custom",onValueChange:S=>{S==="auto"&&i("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(Ye,{type:"number",placeholder:"0",value:String(f.rotation||0),onSave:S=>i("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Fl=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Rl=[0,1,2,3,4,5,6,8,10],Ol=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Pl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Bl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(n.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Vl,{})})]})}function Vl(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(zl,{metricKey:a,idx:r},a))})}function zl({metricKey:s,idx:a}){var w;const[r,l]=C.useState(!1),u=t.useEditorStore(A=>{var B;return(B=A.card)==null?void 0:B.preferences}),c=t.useEditorStore(A=>{var B,S;return(S=(B=A.card)==null?void 0:B.preferences)==null?void 0:S.datasetOptions}),o=c==null?void 0:c.find(A=>A.idx===a),{setCardPreferences:d}=t.useEditorStore(A=>A.actions),i=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",h=((w=o==null?void 0:o.dataLabels)==null?void 0:w.enabled)??!1,v=i==="line"?n.ChartLine:n.ChartColumnIncreasing;function f(A){const B={idx:a,type:i,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...A};if(!o)d({...u||{},datasetOptions:[...c||[],B]});else{const S=c==null?void 0:c.map(E=>E.idx===a?{...E,...B}:E);d({...u||{},datasetOptions:S})}}function m(A){f({type:A})}function g(A){f({yAxisId:A})}function y(A){f({dataLabels:{...o==null?void 0:o.dataLabels,enabled:A}})}function b(A){f({dataLabels:A})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(v,{className:"h-3 w-3"}),i==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Fl.map(({type:A,icon:B,label:S})=>{const E=i===A;return e.jsxs("button",{onClick:()=>m(A),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",E?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:S})]},A)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:x,onValueChange:A=>g(A),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),i==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:A=>f({lineStyle:A}),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:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},A))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:A=>f({pointRadius:Number(A)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Rl.map(A=>e.jsx(t.SelectItem,{value:String(A),className:"text-xs",children:A===0?"None":A},A))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:A=>f({pointStyle:A}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.map(({value:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},A))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:y})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const cs=[{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"}],_l=[0,1,2,3,4,5,6,8,10],ql=[{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 │"}],$l=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Kl(s){return s==null?"origin":s===!1?"false":s}function Gl(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(n.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Ul,{})})]})}function Ul(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(Hl,{metricKey:a,idx:r},a))})}function Hl({metricKey:s,idx:a}){var y;const[r,l]=C.useState(!1),u=t.useEditorStore(b=>{var w;return(w=b.card)==null?void 0:w.preferences}),c=t.useEditorStore(b=>{var w,A;return(A=(w=b.card)==null?void 0:w.preferences)==null?void 0:A.datasetOptions}),o=c==null?void 0:c.find(b=>b.idx===a),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),i=Kl(o==null?void 0:o.fill),x=((y=o==null?void 0:o.dataLabels)==null?void 0:y.enabled)??!1,h=cs.find(b=>b.value===i)||cs[0];function v(b){const w={idx:a,fill:i,dataLabels:o==null?void 0:o.dataLabels,...b};if(!o)d({...u||{},datasetOptions:[...c||[],w]});else{const A=c==null?void 0:c.map(B=>B.idx===a?{...B,...w}:B);d({...u||{},datasetOptions:A})}}function f(b){v({fill:b==="false"?!1:b})}function m(b){v({dataLabels:{...o==null?void 0:o.dataLabels,enabled:b}})}function g(b){v({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(n.ChartArea,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:i,onValueChange:b=>f(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cs.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.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:b=>v({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},b))})]})]}),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:b=>v({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),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:b=>v({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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.Switch,{size:"sm",checked:x,onCheckedChange:m})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ql=[0,1,2,3,4,5,6,8,10],Wl=[{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 │"}],ds=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Jl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="line"?null:e.jsxs(n.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Yl,{})})]})}function Yl(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(Xl,{metricKey:a,idx:r},a))})}function Xl({metricKey:s,idx:a}){var b;const[r,l]=C.useState(!1),u=t.useEditorStore(w=>{var A;return(A=w.card)==null?void 0:A.preferences}),c=t.useEditorStore(w=>{var A,B;return(B=(A=w.card)==null?void 0:A.preferences)==null?void 0:B.datasetOptions}),o=c==null?void 0:c.find(w=>w.idx===a),{setCardPreferences:d}=t.useEditorStore(w=>w.actions),i=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,h=(o==null?void 0:o.pointStyle)||"circle",v=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,f=ds.find(w=>w.value===i)||ds[0];function m(w){const A={idx:a,lineStyle:i,pointRadius:x,pointStyle:h,dataLabels:o==null?void 0:o.dataLabels,...w};if(!o)d({...u||{},datasetOptions:[...c||[],A]});else{const B=c==null?void 0:c.map(S=>S.idx===a?{...S,...A}:S);d({...u||{},datasetOptions:B})}}function g(w){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:w}})}function y(w){m({dataLabels:w})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(n.TrendingUp,{className:"h-3 w-3"}),f.label.split(" ")[0]]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:i,onValueChange:w=>m({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ds.map(({value:w,label:A})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:A},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(x),onValueChange:w=>m({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:Ql.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:h,onValueChange:w=>m({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(({value:w,label:A})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:A},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.Switch,{size:"sm",checked:v,onCheckedChange:g})]}),v&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Zl=[0,2,4,6,8,10,12,16,20];function eo(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(n.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(to,{})})]})}function to(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(so,{metricKey:a,idx:r},a))})}function so({metricKey:s,idx:a}){var g;const[r,l]=C.useState(!1),u=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.type}),c=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.preferences}),o=t.useEditorStore(y=>{var b,w;return(w=(b=y.card)==null?void 0:b.preferences)==null?void 0:w.datasetOptions}),d=o==null?void 0:o.find(y=>y.idx===a),{setCardPreferences:i}=t.useEditorStore(y=>y.actions),x=(d==null?void 0:d.borderRadius)??0,h=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function v(y){const b={idx:a,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...y};if(!d)i({...c||{},datasetOptions:[...o||[],b]});else{const w=o==null?void 0:o.map(A=>A.idx===a?{...A,...b}:A);i({...c||{},datasetOptions:w})}}function f(y){v({dataLabels:{...d==null?void 0:d.dataLabels,enabled:y}})}function m(y){v({dataLabels:y})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(x),onValueChange:y=>v({borderRadius:Number(y)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Zl.map(y=>e.jsx(t.SelectItem,{value:String(y),className:"text-xs",children:y===0?"None":`${y}px`},y))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:f})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:u==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const no=[0,1,2,3,4,5,6,8,10],ao=[{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 │"}],ro=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function lo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var i;return(i=d.card)==null?void 0:i.preferences}),r=Me.useEffectiveEditorCardType(),l=a==null?void 0:a.lineStyleConfig,{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const o=(d,i)=>{const x={...a||{},lineStyleConfig:{...l,[d]:i}};u(x),c({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:d=>o("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ro.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:d=>o("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:no.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:d=>o("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ao.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]})]})})]})}const oo=[0,2,4,6,8,10,12,16,20],io=[{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%"}],co=[{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 uo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var i;return(i=d.card)==null?void 0:i.preferences}),r=Me.useEffectiveEditorCardType(),l=a==null?void 0:a.barStyleConfig,{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const o=(d,i)=>{const x={...a||{},barStyleConfig:{...l,[d]:i}};u(x),c({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.borderRadius)??0),onValueChange:d=>o("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:oo.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.barPercentage)??.9),onValueChange:d=>o("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:io.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.categoryPercentage)??.8),onValueChange:d=>o("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:co.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]})]})})]})}function mo(){const s=t.useEditorStore(r=>{var l,u;return(u=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:u.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(n.AccordionItem,{value:"stacked-sort",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(n.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(at,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})})]})}const xo=["kpi"],En={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},us=2;function ot(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 ho(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const a=t.getDataType(s.dataType);return["date","string","boolean"].includes(a)}function po(s){return{...s,role:"groupby"}}function fo(){var A,B;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),r=Me.useEffectiveEditorCardType(),{scopedFields:l}=n.useScopedFields(),u=((A=s.config)==null?void 0:A.metricColumns)||[],c=((B=s.config)==null?void 0:B.summary)||{},o=c.breakdownDimensions||[],d=xo.includes(r),i=u.length>0,x=c.enabled===!0,h=d&&i,{comparisonType:v}=n.getEffectiveComparisonSettings(s.config,r),f=En[v]||En.none,m=Array.from(new Map(l.filter(ho).map(S=>[ot(S),po(S)])).values()),g=new Set(m.map(S=>ot(S))),y=new Set(o.map(S=>ot(S)).filter(S=>S&&g.has(S)));if(!d)return null;const b=S=>{a(s.id,{summary:{...c,...S}})},w=(S,E)=>{const I=ot(S),T=m.filter(M=>y.has(ot(M))),N=E?y.has(I)?T:[...T,S].slice(0,us):T.filter(M=>ot(M)!==I);b({breakdownDimensions:N})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!i&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:x,disabled:!h,onCheckedChange:S=>{if(!S){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({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: ",f]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!x,onCheckedChange:S=>b({showOnCard:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:S=>b({includeInDashboardSummary:S})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",us]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(S=>{const E=ot(S),I=y.has(E),T=y.size>=us,N=!x||!I&&T;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${E}`,checked:I,disabled:N,onCheckedChange:M=>w(S,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${E}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},E)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!x,onCheckedChange:S=>b({anomalyEnabled:S})})]})]})]})}const go=[];function bo(){var u;const s=t.useEditorStore(c=>c.card),a=((u=s==null?void 0:s.config)==null?void 0:u.metricColumns)??go,{updateMetricColumn:r,updateCardInFrame:l}=t.useEditorActions();return!s||s.type==="kpi"||a.length===0?null:e.jsxs(n.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va.Braces,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 pt-2",children:a.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(js,{value:c.format,onChange:o=>{var d;r(s.id,c.id,{format:o}),l({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(i=>i.id===c.id?{...i,format:o}:i)}})}})]},c.id))})]})}const jo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function vo(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),r=Me.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions();if(!s||!jo.has(r||""))return null;const c=a==null?void 0:a.tooltipConfig,o=(c==null?void 0:c.formatMode)||(c==null?void 0:c.mode)||"inherit",d=i=>{const x={...a||{},tooltipConfig:{...c||{},...i}};l(x),u({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.Switch,{size:"sm",checked:o==="override",onCheckedChange:i=>d({formatMode:i?"override":"inherit",mode:i?"override":"inherit"})})]}),o==="override"&&e.jsx(vt,{formatOptions:(c==null?void 0:c.formatOptions)||{},onFormatOptionsChange:i=>d({formatMode:"override",mode:"override",formatOptions:i}),showTitle:!1})]})]})}function Zn({mode:s}){const a=t.useEditorStore(r=>{var l;return(l=r.card)==null?void 0:l.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Bl,{}),(a==="area"||a==="stackedArea")&&e.jsx(Gl,{}),a==="line"&&e.jsx(Jl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(eo,{}),e.jsx(lo,{}),e.jsx(uo,{}),e.jsx(Cl,{}),s==="config"&&e.jsx(Nl,{}),s==="config"&&e.jsx(fo,{}),e.jsx(wl,{}),a==="bullet"&&e.jsx(Tl,{}),a==="funnel"&&e.jsx(kl,{}),(a==="bubble"||a==="scatter")&&e.jsx(El,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(mo,{}),e.jsx(bo,{}),e.jsx(bl,{}),e.jsx(jl,{}),e.jsx(vl,{}),e.jsx(yl,{}),e.jsx(vo,{})]})}function yo(){const s=t.useEditorStore(r=>r.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Kt,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Zn,{mode:"dev"})})]}):null}function No(){const s=t.useEditorStore(u=>u.card),a=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(n.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(n.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(n.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function l(){switch(a){case"kpi":return e.jsx(Xr,{});case"table":return e.jsx(hl,{});case"map":return e.jsx(sl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Wn,{})});case"text":return e.jsx(fl,{});default:return e.jsx(yo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[l(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Co(){const s=C.useRef(null),a=C.useRef(null),r=t.useEditorStore(g=>g.isShowingVisual),l=t.useEditorStore(g=>g.isDevMode),u=t.useEditorStore(g=>g.showAIDialog),[c,o]=C.useState(!1),d=r&&!u,i=d&&(!l||c),x=l&&d,h=()=>o(g=>!g);C.useEffect(()=>{var g,y,b,w;u?((g=s.current)==null||g.resize(0),(y=a.current)==null||y.resize(0)):((b=s.current)==null||b.resize(25),(w=a.current)==null||w.resize(25))},[u]);const[v,f]=C.useState(!1),m=x?{show:!0,isOpen:c,onToggle:h}:void 0;return e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(n.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:50,children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(mr,{})}),e.jsx(rs,{mode:"toolbar",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})]})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:i?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(rs,{mode:"canvas",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})}),!u&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(No,{})})]}):e.jsx(rs,{mode:"canvas",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})})]})}function So(s){var ye;t.useAIInteractionStore(K=>K.currentAIContext);const[a,r]=C.useState(""),[l,u]=C.useState(null),{authToken:c,tokenProps:o}=n.useSemaphorContext(),d=t.useEditorStore(K=>K.card.id),i=t.useEditorStore(K=>{var Q;return(Q=K==null?void 0:K.card)==null?void 0:Q.sql}),x=t.useEditorStore(K=>K.isDevMode),h=t.useEditorStore(K=>{var Q;return(Q=K==null?void 0:K.card)==null?void 0:Q.python}),{setCardPython:v,setCardSql:f,setRunSql:m,switchCardType:g,setQueryConfig:y}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],w=t.useEditorStore(K=>K.userInputForAI),A=t.useEditorStore(K=>K.triggerAIRun),B=t.useEditorStore(K=>K.card),S=t.useEditorStore(K=>K.selectedDatabaseName),E=t.useEditorStore(K=>K.selectedTableName),I=t.useEditorStore(K=>K.selectedConnectionId),T=t.useEditorStore(K=>K.selectedSchemaName),N=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:M,refetch:j,data:O}=n.useEditorCardQuery(B),{setTriggerAIRun:D,setCurrentAssitantScope:L,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:p,connectionType:F,selectedDatamodelId:k}=n.useEditorAside(),P=(ye=n.useDashboardQuery().data)==null?void 0:ye.assistantProfileId,V=C.useRef(n.createAssistantConversationId()),z=C.useRef(null),_=C.useRef(d),q=C.useRef(!1),W=()=>{const K=z.current;K&&(z.current=null,V.current=n.createAssistantConversationId(),K==="clear"&&U([]))},{messages:$,setMessages:U,regenerate:se,error:ie,sendMessage:le,status:de,addToolResult:me,stop:ue,clearError:Ne}=n.useChat({transport:new n.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:V.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:x,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:Q})=>({body:{...Q,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var Q;if(q.current=!1,K.name==="AbortError"||(Q=K.message)!=null&&Q.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),W();return}console.error("[Editor Assistant] Stream error:",K),W()},onToolCall:je,onFinish({isAbort:K,isDisconnect:Q,isError:te}){q.current=!1,r(""),console.log(K?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":te?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),W()}}),we=C.useCallback(K=>{q.current=!0;try{const Q=le(K);return n.isPromiseLike(Q)?Q.catch(te=>{throw q.current=!1,te}):Q}catch(Q){throw q.current=!1,Q}},[le]),Te=C.useCallback(()=>{q.current=!0;try{const K=se();return n.isPromiseLike(K)?K.catch(Q=>{throw q.current=!1,Q}):K}catch(K){throw q.current=!1,K}},[se]),Z=K=>{let Q=!1;U(te=>{const xe=typeof K=="function"?K(te):K;if(xe.length===0){if(q.current)return z.current="clear",Q=!0,te;z.current=null,V.current=n.createAssistantConversationId()}return xe}),Q&&ue()};C.useEffect(()=>{if(_.current!==d){if(_.current=d,q.current){z.current!=="clear"&&(z.current="rotate"),ue();return}z.current=null,V.current=n.createAssistantConversationId()}},[d,ue]),C.useEffect(()=>{A&&w&&(we({role:"user",parts:[{type:"text",text:w}]}),D(!1))},[A,w,we,D]);async function je({toolCall:K}){var Q,te,xe,pe,Fe,ee,Se,fe,De,Oe,Qe,Ke,Ge,re,ke,ze;if(["createChartFromSql","createForecast"].includes(K.toolName)){const Ce=((Q=K.input)==null?void 0:Q.sql)??((te=K.args)==null?void 0:te.sql),We=((xe=K.input)==null?void 0:xe.python)??((pe=K.args)==null?void 0:pe.python),Ee=((Fe=K.input)==null?void 0:Fe.chartType)??((ee=K.args)==null?void 0:ee.chartType);g(Ee),f(Ce),v(We),m(!0),me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!i){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:i,python:h||""}})}else if(K.toolName==="generateQueryConfig"){r("Generating query config...");const Ce=((Se=K.input)==null?void 0:Se.chartType)??((fe=K.args)==null?void 0:fe.chartType),We=((De=K.input)==null?void 0:De.queryConfig)??((Oe=K.args)==null?void 0:Oe.queryConfig);((Qe=K.input)==null?void 0:Qe.cardConfig)??((Ke=K.args)==null||Ke.cardConfig),g(Ce),R(We),f(void 0),v(void 0);const Ee=await j();if((Ge=Ee==null?void 0:Ee.data)!=null&&Ge.error){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:We,message:(re=Ee==null?void 0:Ee.data)==null?void 0:re.error.message}});return}if((ke=Ee==null?void 0:Ee.data)!=null&&ke.records){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:We,message:"The data has been visualized"}});return}me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:We,message:"The data has been visualized",records:(ze=Ee==null?void 0:Ee.data)==null?void 0:ze.records}})}else r("Analyzing...")}function Ie(K){const Q=n.removeFromScopeArray(b,K);ne(Q)}function ne(K){const Q=n.sanitizeAIScope(K);L(Q),U(te=>[...te,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}]}])}function Ae(){const K={databaseName:S||"",schemaName:T||"",tableName:E||"",datamodelId:k||"",datamodelName:t.resolveDatamodelName(p),connectionId:I||"",connectionType:F||""},Q=n.dedup([...b,K]);ne(Q)}function Le(){const K={databaseName:S||"",schemaName:T||"",tableName:E||"",datamodelName:t.resolveDatamodelName(p),connectionId:I||"",connectionType:F||"",datamodelId:k||""};if(!n.isInAiScopeArray([...N||[],...b],K)||b.length===0){const te=n.dedup([...N||[],...b,K]).filter(xe=>xe.connectionId===K.connectionId);ne(te)}}const ae=!["ready","error"].includes(de),ve=n.getErrorMessage(ie);return{messages:$,setMessages:Z,sendMessage:we,regenerate:Te,isLoading:ae,handleSetAIScope:Le,handleAddCurrentTableToScope:Ae,removeFromCurrentSelections:Ie,currentAssitantScope:b,setCurrentAssitantScope:L,stop:ue,status:de,toolStatus:a,llmUsage:l,onFinish:s,errorMessage:ve,clearError:Ne}}const wo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function In({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const l=C.useRef(null),u=C.useRef(!1),[c,o]=C.useState(!1),[d,i]=C.useState(t.isDevEnv),[x,h]=C.useState(!1),[v,f]=C.useState(!1),[m,g]=C.useState(!1),y=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:w,setHasEditorEntitySelectionOverride:A}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:S}=t.useFileActions(),E=t.useFileAttachments("editor"),{selectedEntities:I}=n.useAssistantContextEntities("editor"),T=t.useEditorStore(re=>re.card.id),N=t.useEditorStore(re=>re.card.dataSource),M=t.useEditorStore(re=>{var ke;return(ke=re.card.dataSource)==null?void 0:ke.selectedEntities}),j=t.useEditorStore(re=>re.actions.setCardSql),O=t.useEditorStore(re=>re.actions.setRunSql),D=t.useEditorStore(re=>re.showAIDialog),L=t.useDashboardStore(re=>re.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:p}=t.useEditorActions(),{setDataSource:F}=t.useEditorActions(),{assistantProfile:k}=n.useAssistantProfile(),{messages:P,setMessages:V,sendMessage:z,isLoading:_,stop:q,status:W,llmUsage:$,errorMessage:U,clearError:se}=So(),[ie,le]=C.useState(""),de=re=>{le(re.target.value)},me=re=>{re.preventDefault();const ke=ie.trim();if(!ke&&E.length===0)return;const ze=[];ke&&ze.push({type:"text",text:ke}),E.forEach(Ce=>{Ce.data&&ze.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),z({role:"user",parts:ze}),le(""),S("editor"),ae({force:!0})},{visibleMessages:ue,hasMoreMessages:Ne,totalMessageCount:we,loadMoreMessages:Te,resetMessageWindow:Z}=n.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:je,contentRef:Ie,isAtBottom:ne,hasNewMessages:Ae,newMessageCount:Le,scrollToBottom:ae,handleScroll:ve,resetNewMessageCount:ye}=n.useAutoScroll(ue,{threshold:40,behavior:"smooth",isStreaming:_});C.useEffect(()=>{var re;D&&!u.current&&((re=l.current)==null||re.focus()),u.current=D},[D]),C.useEffect(()=>{D&&(A(!1),w({selectedEntities:M||[]}))},[T,M,w,A,D]),n.useAutoSubmitQueue({assistantType:"editor",status:W,isLoading:_,sendMessage:z});const{hasActiveTools:K,activeToolText:Q}=n.useActiveToolStatus(P),te=C.useCallback(re=>{a==null||a(re),s===void 0&&g(re)},[s,a]);C.useEffect(()=>{if(!y)return;function re(ke){ke.key==="Escape"&&te(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[y,te]);const xe=C.useCallback(re=>{z({role:"user",parts:[{type:"text",text:re}]}),ae({force:!0})},[z,ae]),pe=C.useCallback(async()=>{const re=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),n.ue.success("Conversation copied")}catch(ke){console.error("Failed to copy conversation",ke),n.ue.error("Unable to copy conversation")}},[P]),Fe=C.useCallback(()=>{te(!y)},[y,te]);function ee(re,ke){ke==="sql"?(j(re),O(!0)):ke==="python"&&(p(re),O(!0))}function Se(){b.selectedEntities.length===0&&w({selectedEntities:I})}function fe(re){Se();const ke={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};z(ke)}function De(re){Se(),z({role:"user",parts:[{type:"text",text:re}]})}function Oe(){return e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(n.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",children:[e.jsx(n.DropdownMenuLabel,{children:"Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Token Usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:h,children:"System Message"})]})]})}function Qe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ke=(ie==null?void 0:ie.length)===0&&(P==null?void 0:P.filter(re=>re.role==="user").length)===0,Ge=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Qe(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Oe(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:pe,children:"Copy Conversation"}),e.jsx(n.IconButton,{tooltip:y?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Fe,children:y?e.jsx(n.Minimize2,{className:"size-4"}):e.jsx(n.Maximize2,{className:"size-4"})}),e.jsx(n.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{V([]),B("editor"),se(),Z()},children:e.jsx(n.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(n.CustomScrollArea,{ref:je,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:ve,children:e.jsxs("div",{ref:Ie,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[Ne&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:Te,className:"text-xs",children:["Load ",Math.min(5,we-ue.length)," ","more messages (",we-ue.length," ","hidden)"]})}),e.jsx(n.PrintMessages,{messages:ue,showTools:d,handleRun:ee,showSystemMessage:x,onQuickReply:xe,disableQuickReplies:_}),e.jsx(n.AssistantStatus,{status:W,errorMessage:U,activeToolText:_&&K?Q:void 0})]})}),D&&!ne&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{ae({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),Ae&&Le>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:Le>9?"9+":Le})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ke&&!k&&e.jsx(n.Placeholders,{onClick:fe,placeholders:wo}),e.jsx("div",{children:Ke&&k&&e.jsx(n.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:De})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:l,setInput:le,stop:q,input:ie,handleInputChange:de,handleSubmit:re=>{Se(),me(re),ae({force:!0})},isLoading:_,status:W,assistantType:"editor",onFocus:()=>{}})]}),$&&c&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",$.inputTokens," prompt tokens, ",$.outputTokens," ","completion tokens, ",$.totalTokens," total tokens"]})}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:I,open:v,onOpenChange:f,dataSource:N||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:re=>{A(!0),w({...b,selectedEntities:re})}})]});return y&&r?ba.createPortal(e.jsx(n.SemaphorStyleWrapper,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:Ge})}),r):Ge}function To(s,a,r){if(!a)return!1;const l=a.qualifiedFieldName,u=a.qualifiedEntityName,c=u&&a.name?`${u}.${a.name}`:l;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const i=n.getSelectedDateFilterColumn(o,r),x=i.split("."),h=x[x.length-1]||i,v=x.length>1?x.slice(0,-1).join("."):void 0,f=o.qualifiedTableName||v,m=f?`${f}.${h}`:void 0;return l?m?m===c||m.endsWith(`.${l}`):h===a.name:m?m===c:h===a.name})}function Eo({aliasTemplate:s,onAliasTemplateChange:a}){var i;const[r,l]=C.useState(s),[u,c]=C.useState(!1),o=(i=t.useEditorStore(x=>{var h;return(h=x.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:i[0],d=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:d,value:u?r:s,onChange:x=>{l(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&u&&r!==s?(a(r),c(!1)):x.key==="Escape"&&(l(s),c(!1))},"aria-label":"Edit alias template"}),u&&r!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(r),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:()=>{l(s),c(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Io({valueAliases:s,onValueAliasesChange:a}){const[r,l]=C.useState(null),[u,c]=C.useState(""),[o,d]=C.useState(""),i=()=>{a({...s,"":""})},x=v=>{const f={...s};delete f[v],a(f)},h=v=>{const f={...s};delete f[v],f[u]=o,a(f),l(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([v,f],m)=>e.jsx("div",{className:"flex items-center gap-2",children:r===v?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:u,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:o,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(v),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>l(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:v,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{l(v),c(v),d(f)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{l(v),c(v),d(f)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(v),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},v+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:i,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function ko({idx:s}){var d;const a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),r=t.useEditorStore(i=>{var x;return(x=i.card.preferences)==null?void 0:x.datasetOptions}),l=t.useEditorStore(i=>i.actions.setCardPreferences),u=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,c=r==null?void 0:r.find(i=>i.idx===s);function o(i,x){(i==="end"||i==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:i!=="none",align:i,anchor:i,clamp:!0};if(!c)l({...a,datasetOptions:[...r||[],{idx:x,datalabels:h}]});else{const v={...c};v.datalabels=h;const f=r==null?void 0:r.map(m=>m.idx===x?v:m);l({...a,datasetOptions:f})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(za,{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(ka,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Aa,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})})]})})]})}function vs({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function Do(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Ao({col:s,idx:a,className:r,iconClassName:l,children:u}){const c=t.useEditorStore(h=>{var v;return(v=h.card)==null?void 0:v.preferences}),o=t.useEditorStore(h=>{var v,f;return(f=(v=h.card)==null?void 0:v.preferences)==null?void 0:f.datasetOptions}),d=o==null?void 0:o.find(h=>h.idx===a),{setCardPreferences:i}=t.useEditorStore(h=>h.actions);function x(h){if(!d)i({...c,datasetOptions:[...o||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const v={...d};v.type=h==="area"?"line":h,v.fill=h==="area"?"origin":"";const f=o==null?void 0:o.map(m=>m.idx===a?v:m);i({...c,datasetOptions:f})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[u||e.jsx(vs,{className:"max-w-[100px]",title:s,children:Do(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(ko,{idx:a})]})]})}function Mo(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),r=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:l}=t.useEditorStore(d=>d.actions);function u(d){var h;const i={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(h=r==null?void 0:r.chartOptions)==null?void 0:h.plugins,...i}}};l(x)}function c(){var d,i,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(i=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:i.datalabels)==null?void 0:x.anchor)||"none",onValueChange:u,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function o(){var d,i,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(i=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:i.datalabels)==null?void 0:x.anchor)||"none",onValueChange:u,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?c():o()})}function Lo({column:s}){const a=t.useEditorStore(i=>i.card.type),r=t.useEditorStore(i=>{var x,h;return(h=(x=i.card)==null?void 0:x.config)==null?void 0:h.metricColumns}),l=(r==null?void 0:r.map(i=>i.label))||[],u=l==null?void 0:l.find(i=>i===s.label||i===s.name),c=u?l.indexOf(u):-1;function o(){return e.jsx("div",{className:"pr-1",children:u&&e.jsx(Ao,{idx:c,col:u,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Mo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&o(),["pie","doughnut"].includes(a)&&d()]})}function Fo({field:s,searchQuery:a="",limit:r=500}){const{authToken:l,tokenProps:u}=n.useSemaphorContext(),c=t.useEditorStore(x=>x.card),o=c==null?void 0:c.dataSource,d=["attribute-values",s.entityName,s.name,a,r],i=n.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:r},h={connection_id:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:t.getCacheConfig({card:c})};console.log("requestBody",h);const v=await t.postRequestRegular(`${u.apiServiceUrl}/v1/query`,(l==null?void 0:l.accessToken)||"",h);if(v!=null&&v.error)return console.error("Error fetching attribute values:",v.error),[];const f=s.name;return((v==null?void 0:v.records)||[]).map(g=>{const y=g[f]||g[s.alias||f]||g[s.label];return{id:y||"",value:y||"",label:String(y||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function ea({open:s,onOpenChange:a,availableFields:r,existingFilters:l,editingCondition:u,onSave:c}){var B,S;const o=!!u,[d,i]=C.useState(o?"values":"fields"),[x,h]=C.useState(""),[v,f]=C.useState({id:(u==null?void 0:u.id)||t.v4(),field:(u==null?void 0:u.field)||null,selectedValues:u?Array.isArray(u.value)?u.value:[u.value]:[]}),m=r.filter(E=>{var T;return o?!1:!((T=l==null?void 0:l.conditions)==null?void 0:T.some(N=>N.field.id===E.id))&&E.label.toLowerCase().includes(x.toLowerCase())}),g=E=>{f({...v,field:E}),i("values")},y=()=>{if(v.field&&v.selectedValues.length>0){const E={id:v.id,field:v.field,operator:"in",value:v.selectedValues};let I;if(o){const T=((l==null?void 0:l.conditions)||[]).map(N=>N.id===u.id?E:N);I={...l,conditions:T}}else{const T=(l==null?void 0:l.conditions)||[];I={id:(l==null?void 0:l.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...T,E],groups:[]}}c(I),a(!1)}},b=()=>{if(!o||!u)return;const E=((l==null?void 0:l.conditions)||[]).filter(I=>I.id!==u.id);if(E.length>0){const I={...l,conditions:E};c(I)}else c(void 0);a(!1)},w=E=>{f({...v,selectedValues:E})},A=()=>{o&&u?(f({id:u.id,field:u.field,selectedValues:Array.isArray(u.value)?u.value:[u.value]}),i("values")):(f({id:t.v4(),field:null,selectedValues:[]}),i("fields")),h("")};return C.useEffect(()=>{s&&A()},[s,o,u]),e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-2xl",children:[e.jsx(n.DialogHeader,{children:e.jsx(n.DialogTitle,{children:o?`Edit Filter: ${(B=v.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(S=v.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(l==null?void 0:l.conditions)&&l.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.conditions.map(E=>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:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),d==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:x,onChange:E=>h(E.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),x&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>h(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:m.map(E=>e.jsxs("button",{type:"button",onClick:()=>g(E),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(n.IconForFieldType,{dataType:t.getDataType(E.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:E.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),m.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),m.length===0&&!x&&r.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ro,{field:v.field,selectedValues:v.selectedValues,onValuesChange:w,onBack:o?void 0:()=>i("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:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:A,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:y,disabled:!v.field||v.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ro({field:s,selectedValues:a,onValuesChange:r,onBack:l}){const[u,c]=C.useState(""),{values:o,isLoading:d,isFetching:i}=Fo({field:s,searchQuery:u,limit:500}),x=u?o.filter(f=>String(f.value).toLowerCase().includes(u.toLowerCase())):o,h=f=>{const m=a.includes(f);r(m?a.filter(g=>g!==f):[...a,f])},v=()=>{a.length===x.length&&x.length>0?r([]):r(x.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:l,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(n.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:u,onChange:f=>c(f.target.value),className:"pl-10"})]}),d||i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(n.Checkbox,{checked:a.length===x.length&&x.length>0,onCheckedChange:v}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>h(f.value),children:[e.jsx(n.Checkbox,{checked:a.includes(f.value),onCheckedChange:()=>h(f.value)}),e.jsx(vs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function Oo({field:s,zone:a,index:r,sortDirection:l,onSortDirectionChange:u,hasPivotColumns:c=!1,cardType:o}){var Es,Is,ks,Ds,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Ws,Js,Ys,Xs,Zs,en,tn,sn,nn,an,rn;const{attributes:d,listeners:i,setNodeRef:x,transform:h,transition:v,isDragging:f}=n.useSortable({id:s.id}),m=t.useEditorStore(H=>H.card),g=t.useEditorStore(H=>H.frame),y=t.useDashboardStore(H=>H.isVisualEditing),b=t.useDashboardStore(H=>H.selectedSheetId),w=t.useDashboardStore(H=>H.actions.updateSheetCalculatedFields),{scopedFields:A,valuePickFilterableFields:B,isLoading:S}=n.useFilterableFields(),{userContext:E}=n.useCurrentUserInfo(),I=(E==null?void 0:E.type)==="organization",{updateLabel:T,handleAggregationChange:N,handleDateFormatChange:M,handleGranularityChange:j,handleAliasTemplateChange:O,handleValueAliasesChange:D,handleMetricFormatChange:L,removeField:R,handleMetricComparisonChange:p,handleMetricWindowTransformChange:F,handleMetricWindowOrderByChange:k,handleMetricWindowDirectionChange:P,handleMetricWindowPartitionToggle:V,handleMetricMovingAverageWindowSizeChange:z,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:q,handleMetricPercentOfTotalScopeChange:W,handleMetricPercentOfTotalOutputChange:$,handleKpiShowTrendlineChange:U,handleKpiTrendlineWindowChange:se,handleKpiTrendlineGranularityChange:ie,handleMetricTargetValueChange:le}=n.useFieldManagement(m),[de,me]=C.useState(!1),[ue,Ne]=C.useState(()=>{var H;return!!((H=s.parameters)!=null&&H.windowTransform)}),[we,Te]=C.useState(!1),[Z,je]=C.useState(!1),[Ie,ne]=C.useState(null),Ae=C.useMemo(()=>{const H=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Y=H(s.id),he=A.find(oe=>{if(s.qualifiedFieldName&&oe.qualifiedFieldName&&oe.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&oe.qualifiedEntityName&&oe.qualifiedEntityName===s.qualifiedEntityName&&oe.name===s.name)return!0;const Re=H(oe.id);return!!(Y&&Re&&Y===Re)});return{dataType:(he==null?void 0:he.dataType)||s.dataType,resolvedFromScopedField:!!he}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,A]),Le=n.getGranularityOptionsForFieldType(Ae.dataType),[ae,ve]=C.useState(s.dateFormat||"YYYY-MM-DD"),[ye,K]=C.useState(s.customFormat||""),[Q,te]=C.useState(!!s.customFormat),xe=C.useRef(null),[pe,Fe]=C.useState(s.aliasTemplate||""),[ee,Se]=C.useState(s.valueAliases||{}),[fe,De]=C.useState((Es=s.parameters)==null?void 0:Es.filters),Oe=H=>{H==="custom"?te(!0):(te(!1),ve(H),(a==="groupBy"||xt)&&M(r,H,"",a))},Qe=H=>{K(H),(a==="groupBy"||xt)&&M(r,"custom",H,a)},Ke=H=>{var oe;const he=(oe=n.getDateFormatOptionsForGranularity(H)[0])==null?void 0:oe.value;he&&!Q&&(ve(he),a==="groupBy"&&M(r,he,"",a)),a==="groupBy"&&j(r,H)},Ge=H=>{Fe(H),a==="metrics"&&O(r,H)},re=H=>{Se(H),a==="metrics"&&D(r,H)},ke=H=>{T(a,r,H)},ze=n.getExpressionFieldKind(s),Ce=n.getFieldExpressionAnnotation(s),We=n.isManagedCalculatedExpressionField(s),Ee=s.role==="metric"&&We,yt=We&&(ze==="user_calculated"||ze==="inline_expression"&&s.fieldScope!=="domain"),Ze=yt?(Is=g==null?void 0:g.calculatedFields)==null?void 0:Is.find(H=>t.matchesCalculatedField(H,s,{allowComparableFallback:!0})):void 0,kt=yt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Ze),Je=ze==="domain_calculated"||s.fieldScope==="domain",Dt=Je?n.resolveDomainCalculatedFieldForEdit(s,A):void 0,dt=Je?"domain":kt?"dashboard":"card",et=Je?Dt||s:kt&&Ze?Ze:s,At=H=>{var Y;if(De(H),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:H}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}Te(!1)},Nt=()=>{R(a,r)},Ht={transform:n.CSS.Transform.toString(h),transition:v},Mt=t.getDataType(Ae.dataType||s.dataType),ut=Mt==="date",mt=o==="kpi",xt=a==="detailColumns",ht=(ks=m.config)==null?void 0:ks.metricColumns,Ue=(Ds=m.config)==null?void 0:Ds.groupByColumns,tt=t.useDashboardStore(H=>{var Y;return(Y=H.dashboard)==null?void 0:Y.filters}),Qt=t.useDashboardStore(H=>H.filterValues),st=s.granularity||"day",Lt=Le.includes(st)?st:"day",Ct=a==="groupBy"&&!Le.includes(st),pt=n.getDateFormatOptionsForGranularity(Lt),Wt=Q?"custom":pt.some(H=>H.value===ae)?ae:((As=pt[0])==null?void 0:As.value)??"YYYY-MM-DD";C.useEffect(()=>{var he;if(S||!Ct){xe.current=null;return}const H=`${s.id}:${st}:${Ae.dataType||s.dataType||""}:${r}`;if(xe.current===H)return;xe.current=H;const Y="day";if(j(r,Y),!Q){const oe=(he=n.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:he.value;oe&&(ve(oe),M(r,oe,"",a))}},[s.dataType,s.id,M,j,Ct,r,Q,S,st,Ae.dataType,a]);const Jt=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Yt=o==="kpi"||o==="table",He=C.useMemo(()=>Ue==null?void 0:Ue.find(H=>t.getDataType(H.dataType||"")==="date"),[Ue]),Ft=C.useMemo(()=>(Ue||[]).some(H=>t.getDataType(H.dataType||"")==="date"),[Ue]),ft=C.useMemo(()=>{var oe;if(!He)return!1;const H=(oe=m.config)==null?void 0:oe.filters;if(!H)return!1;const Y=Re=>{const Be=Re.field;return Be?He.id&&Be.id===He.id||He.qualifiedFieldName&&Be.qualifiedFieldName===He.qualifiedFieldName?!0:Be.name===He.name:!1},he=Re=>Re.conditions.some(qe=>t.getDataType(qe.field.dataType||"")==="date"&&Y(qe))?!0:Re.groups.some(qe=>he(qe));return he(H)},[(Ms=m.config)==null?void 0:Ms.filters,He]),Rt=C.useMemo(()=>To(tt||[],He,Qt),[tt,Qt,He]),St=ft||Rt,G=s,X=((Fs=(Ls=G.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.function)||"none",J=n.isMetricTransformEnabled(G),ce=J?X:null,ge=n.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:m.config||{},metric:G,transformMode:ce||"running_total"}),be=!!G.comparisonType&&G.comparisonType!=="none",Pe=n.getRunningTotalOrderByCandidates(Ue||[]),Ve=((Ps=(Os=(Rs=G.parameters)==null?void 0:Rs.windowTransform)==null?void 0:Os.orderBy)==null?void 0:Ps.fieldId)||"",Xe=((zs=(Vs=(Bs=G.parameters)==null?void 0:Bs.windowTransform)==null?void 0:Vs.orderBy)==null?void 0:zs.direction)||"asc",lt=Pe.find(H=>H.id===Ve),nt=ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta",_e=J&&nt&&!!lt&&t.getDataType(lt.dataType||"")!=="date",gt=n.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:m.config||{},orderByFieldId:Ve||void 0}),Xt=new Set(((qs=(_s=G.parameters)==null?void 0:_s.windowTransform)==null?void 0:qs.partitionByFieldIds)||gt),Zt=o==="pivotTable"||n.isSubtotalEnabledAggregateTable(o||"table",m.config||{}),Ns=[...(Ue||[]).filter(H=>H.id&&(!nt||H.id!==Ve)),...Zt?((($s=m.config)==null?void 0:$s.pivotByColumns)||[]).filter(H=>H.id):[]],Cs=((Us=(Gs=(Ks=G.parameters)==null?void 0:Ks.windowTransform)==null?void 0:Gs.movingAverage)==null?void 0:Us.windowSize)||7,sa=((Ws=(Qs=(Hs=G.parameters)==null?void 0:Hs.windowTransform)==null?void 0:Qs.movingAverage)==null?void 0:Ws.minPeriods)||1,na=((Xs=(Ys=(Js=G.parameters)==null?void 0:Js.windowTransform)==null?void 0:Ys.previousPeriodDelta)==null?void 0:Xs.mode)||"absolute",Ss=((tn=(en=(Zs=G.parameters)==null?void 0:Zs.windowTransform)==null?void 0:en.percentOfTotal)==null?void 0:tn.scope)||"grand_total",aa=((an=(nn=(sn=G.parameters)==null?void 0:sn.windowTransform)==null?void 0:nn.percentOfTotal)==null?void 0:an.output)||"percent",ra=C.useMemo(()=>(ht||[]).some(H=>H.comparisonType==="start_vs_end"),[ht]);C.useEffect(()=>{J&&Ne(!0)},[J]);const la=a!=="pivotBy"&&a!=="sortBy",oa=ut&&a==="groupBy"&&(!mt||ra),ia=!mt&&ut&&(a==="groupBy"||xt),ca=o==="kpi"&&ut&&a==="groupBy",da=a==="metrics",ws=Jt&&a==="metrics",ua=()=>{const H=s,Y=a==="metrics"&&Ee;return e.jsxs("div",{className:"space-y-1",children:[!Y&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:he=>{he.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Y&&H.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(H.calculatedFormula),onPointerDown:he=>{he.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",n.formatDisplayFormula(H.calculatedFormula)]})]})},ma=()=>la?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ye,{value:s.label??"",onSave:ke,placeholder:"Display label...",type:"text"})]}):null,xa=()=>a!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:l||"asc",onValueChange:H=>u(H),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),Ts=()=>oa?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:Lt,onValueChange:Ke,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:Le.map(H=>e.jsx(t.SelectItem,{className:"text-xs",value:H,children:t.toTitleCase(H)},H))})]})]}):null,ha=()=>ia?e.jsxs(e.Fragment,{children:[Ts(),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:Wt,onValueChange:Oe,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:pt.map(H=>e.jsx(t.SelectItem,{className:"text-xs",value:H.value,children:H.label},H.value))})]}),Q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:ye,onChange:H=>{H.stopPropagation(),Qe(H.target.value)},onClick:H=>H.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,pa=()=>{var Y,he,oe,Re;const H=ca;return H?e.jsx(e.Fragment,{children:H&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:U})]})}),((he=m.config)==null?void 0:he.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input,{type:"number",min:"1",max:"365",value:((oe=m.config)==null?void 0:oe.trendlineWindow)||30,onChange:Be=>{const qe=parseInt(Be.target.value)||30;se(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:((Re=m.config)==null?void 0:Re.trendlineGranularity)||"day",onValueChange:ie,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},fa=()=>{if(!da)return null;const H=Ee;return e.jsxs(e.Fragment,{children:[H&&I&&!Je&&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:()=>je(!0),children:[e.jsx(n.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Y=>{N(r,Y)},disabled:H,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(js,{value:G.format,onChange:Y=>L(r,Y),showTitle:!1})]}),e.jsx(n.Collapsible,{open:ue,onOpenChange:Ne,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!ue&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(X.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",ue?"rotate-180":"")})]})]})}),e.jsxs(n.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:J?X:"none",onValueChange:Y=>F(r,Y),disabled:!ge.supported&&!J,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:be,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:be,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:be,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:be,children:"Percent of Total"})]})]}),!ge.supported&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ge.reason}),be&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&e.jsxs(e.Fragment,{children:[nt&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:Ve,onValueChange:Y=>k(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Pe.filter(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Ve&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),_e&&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:Xe,onValueChange:Y=>P(r,Y),disabled:!Ve,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),ce==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input,{type:"number",min:1,className:"h-8 text-xs",value:Cs,onChange:Y=>z(r,Number(Y.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:Cs,className:"h-8 text-xs",value:sa,onChange:Y=>_(r,Number(Y.target.value))})]}),ce==="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:na,onValueChange:Y=>q(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),ce==="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:Ss,onValueChange:Y=>W(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:aa,onValueChange:Y=>$(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta"||ce==="percent_of_total"&&Ss==="partition_total")&&Ns.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:Ns.map(Y=>{const he=!!Y.id&&Xt.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&V(r,Y.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",he?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Y.label||Y.name}),he?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.id)})})]})]})]})]})}),ws&&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:G.comparisonType||"none",disabled:J,onValueChange:Y=>p(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Y=!Ft||!St,he=Ft?St?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(Re,Be)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Re,disabled:Y,title:he,children:Be})}),Y&&he&&e.jsx(t.TooltipContent,{side:"right",children:he})]})});return e.jsxs(e.Fragment,{children:[oe("previous_period","Previous Period"),oe("same_period_last_year","Same Period Last Year"),oe("start_vs_end","Start vs End")]})})(),Yt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),ws&&G.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input,{type:"number",value:G.targetValue!==void 0&&G.targetValue!==null?String(G.targetValue):"",onChange:Y=>{const he=Y.target.value;if(he===""){le(r,void 0);return}const oe=Number(he);le(r,Number.isFinite(oe)?oe: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"}),(fe==null?void 0:fe.conditions)&&fe.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:fe.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{ne(Y),Te(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((he,oe)=>e.jsx("div",{children:String(he)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:he=>{var Re;he.stopPropagation();const oe=fe.conditions.filter(Be=>Be.id!==Y.id);if(oe.length>0){const Be={...fe,conditions:oe};At(Be)}else if(De(void 0),a==="metrics"){const Be={...s,parameters:{...s.parameters,filters:void 0}},qe=[...((Re=m.config)==null?void 0:Re.metricColumns)||[]];qe[r]=Be,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:qe})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ne(null),Te(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Lo,{column:s}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Eo,{aliasTemplate:pe,onAliasTemplateChange:Ge}),e.jsx(Io,{valueAliases:ee,onValueAliasesChange:re})]})]})};fe!=null&&fe.conditions&&fe.conditions.length>0;const ga=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:de,onOpenChange:me,children:[e.jsxs("div",{ref:x,style:Ht,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",de?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",f&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...d,...i,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${n.getMetricDisplayLabel(s)}`,onClick:H=>{H.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:Mt,calculated:!!Ce}),e.jsx(vs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((rn=fe==null?void 0:fe.conditions)==null?void 0:rn.length)&&!de&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(n.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:fe.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:fe.conditions.map(H=>e.jsxs("div",{children:[H.field.label,":"," ",Array.isArray(H.value)?`${H.value.length} values`:String(H.value)]},H.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":l==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:H=>{H.stopPropagation(),u(l==="asc"?"desc":"asc")},children:l==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),ga&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:H=>H.stopPropagation(),children:e.jsx(n.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:H=>{H.stopPropagation(),Nt()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[ua(),xa(),ma(),o==="kpi"&&Ts(),ha(),pa(),fa()]})})]}),we&&e.jsx(ea,{open:we,onOpenChange:H=>{Te(H),H||ne(null)},availableFields:B,existingFilters:fe,editingCondition:Ie,onSave:H=>{var Y;if(H)At(H);else if(De(void 0),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}ne(null)}}),Z&&a==="metrics"&&Ee&&e.jsx(n.CalculatedFieldEditor,{open:Z,onOpenChange:je,availableFields:A,existingField:et,existingFieldScope:dt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:H=>{var Pt;if(H.role!=="metric")return;const{card:Y,frame:he,actions:oe}=t.useEditorStore.getState(),Re=((Pt=Y.config)==null?void 0:Pt.metricColumns)||[],Be=he.calculatedFields||[],{nextActiveFields:qe,nextStoredFields:wt,nextSharedFields:Ot}=n.saveCalculatedFieldToCardScope({activeFields:Re,storedFields:Y.calculatedFields||[],sharedFields:Be,updatedField:H,editingField:et,previousScope:dt});qe&&oe.updateCardConfig(m.id,{metricColumns:qe}),oe.updateCard(m.id,{calculatedFields:wt}),Ot!==Be&&n.commitSharedCalculatedFields({nextSharedFields:Ot,currentSharedFields:Be,isVisualEditing:y,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w})},onSaveToDashboard:H=>{var ln;if(H.role!=="metric")return;const{card:Y,frame:he,actions:oe}=t.useEditorStore.getState(),Re=s,Be=((ln=Y.config)==null?void 0:ln.metricColumns)||[],qe=he.calculatedFields||[],{nextActiveFields:wt,nextStoredFields:Ot,nextSharedFields:Pt}=n.saveCalculatedFieldToSharedScope({activeFields:Be,storedFields:Y.calculatedFields||[],sharedFields:qe,updatedField:{...H,id:Re.id,aliasTemplate:Re.aliasTemplate,valueAliases:Re.valueAliases,parameters:Re.parameters,customFormat:Re.customFormat},editingField:et,previousScope:dt});n.commitSharedCalculatedFields({nextSharedFields:Pt,currentSharedFields:qe,isVisualEditing:y,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w}),wt&&oe.updateCardConfig(m.id,{metricColumns:wt}),oe.updateCard(m.id,{calculatedFields:Ot})},cardId:m.id})]})}function Po({concept:s}){const{title:a,description:r}=Bo[s];return e.jsxs(n.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(n.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(n.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-control border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(Vo,{highlight:s})]})]})}const Bo={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function Vo({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",l=s==="metrics",u="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-control border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(c=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&u),children:c},c))]})}),e.jsx("tbody",{children:kn.map((c,o)=>e.jsxs("tr",{className:t.cn(o!==kn.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",r&&u),children:c.label}),c.values.map((d,i)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",l&&u),children:d},i))]},c.label))})]})})}const kn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],zo={groupBy:$t,pivotBy:hs,metrics:Oa,detailColumns:t.Table2,sortBy:An};function Et({zone:s,fields:a,label:r,placeholder:l,shouldShow:u,hasPivotColumns:c=!1,activeField:o=null}){const{isOver:d,setNodeRef:i}=n.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),h=t.useEditorStore(w=>w.card),v=t.useEditorStore(w=>w.card.type),f=a.length>0,m=C.useMemo(()=>!o||!d?!0:n.validateFieldForChartType(o,s,v).isValid,[o,d,s,v]),g=(w,A)=>{var S;!((S=h.config)!=null&&S.sortByColumns)||h.config.sortByColumns.findIndex(E=>E.id===w)===-1||x(h.id,w,{direction:A})};if(s==="sortBy"&&u===!1)return null;const y=s!=="sortBy"&&v!=="kpi",b=zo[s]||n.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r}),e.jsx("div",{ref:i,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":d&&m,"border border-destructive/40 bg-destructive/5":d&&!m,"border border-dashed border-border/50 bg-background":!d&&!f}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(b,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:l}),y&&e.jsx(Po,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(w=>w.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((w,A)=>{const S=w.direction;return e.jsx(Oo,{field:w,zone:s,index:A,sortDirection:S,onSortDirectionChange:E=>g(w.id,E),hasPivotColumns:c,cardType:v},w.id)})})})})]})}function _o({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:l,detailFields:u,activeField:c}){var _,q,W;const[o,d]=C.useState(!1);t.useEditorStore($=>{var U;return!!((U=$.card.customCardPreferences)!=null&&U.url)});const i=t.useEditorStore($=>$.card),x=t.useEditorStore($=>$.frame),h=n.findCustomVisualConfigCard(x,i),{manifest:v}=n.useCustomVisual(((_=h==null?void 0:h.customCardPreferences)==null?void 0:_.url)||""),f=(q=v==null?void 0:v.visuals)==null?void 0:q.find($=>{var U;return $.name===((U=h==null?void 0:h.customCardPreferences)==null?void 0:U.componentName)}),m=n.resolveMultiInputType(h,f)==="multiple";m&&((W=h==null?void 0:h.customCardPreferences)!=null&&W.url);const g=n.getConfigSlotExpectedType(f==null?void 0:f.slots),y=t.useEditorStore($=>$.actions.updateCardConfig),b=t.useEditorStore($=>$.actions.updateCard),w=t.useEditorStore($=>$.actions.updateFrame),A=t.useDashboardStore($=>$.isVisualEditing),B=t.useDashboardStore($=>$.selectedSheetId),S=t.useDashboardStore($=>$.actions.updateSheetCalculatedFields),{scopedFields:E}=n.useScopedFields(),{userContext:I}=n.useCurrentUserInfo(),T=m&&(h==null?void 0:h.id)===i.id&&g?g:i==null?void 0:i.type,N=T==="detailTable",M=s.length>0||r.length>0||u.length>0,j=!N&&(T!=="kpi"||r.length<=2),O=!N,D=!N&&T!=="kpi",L=T!=="kpi"&&M,R=N,p="Drop sort fields here",F=(I==null?void 0:I.type)==="organization",k=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),P=D&&!k,V=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},z=()=>T==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),M&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{y(i.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[j&&e.jsx(Et,{zone:"groupBy",fields:s,label:V().label,placeholder:V().placeholder,activeField:c}),P&&e.jsx(Et,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:c}),O&&e.jsx(Et,{zone:"metrics",fields:r,label:z().label,placeholder:z().placeholder,hasPivotColumns:a.length>0,activeField:c}),R&&e.jsx(Et,{zone:"detailColumns",fields:u,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&F&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),L&&e.jsx(Et,{zone:"sortBy",fields:l,label:"Sort By",placeholder:p,activeField:c})]}),e.jsx(n.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:E,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{if($.role!=="metric")return;const{nextStoredFields:U}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:i.calculatedFields||[],sharedFields:x.calculatedFields||[],updatedField:$,previousScope:"card"});b(i.id,{calculatedFields:U})},onSaveToDashboard:$=>{if($.role!=="metric")return;const U=x.calculatedFields||[],{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:i.calculatedFields||[],sharedFields:U,updatedField:$,previousScope:"dashboard"});n.commitSharedCalculatedFields({nextSharedFields:se,currentSharedFields:U,isVisualEditing:A,selectedSheetId:B,updateFrame:w,updateSheetCalculatedFields:S})},cardId:i.id})]})}function qo(){var g,y,b;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),u=t.useEditorStore(w=>{var A;return!!((A=w.card.customCardPreferences)!=null&&A.url)}),c=t.useEditorStore(w=>w.card),o=t.useEditorStore(w=>w.frame),d=n.findCustomVisualConfigCard(o,c),{manifest:i}=n.useCustomVisual(((g=d==null?void 0:d.customCardPreferences)==null?void 0:g.url)||""),x=(y=i==null?void 0:i.visuals)==null?void 0:y.find(w=>{var A;return w.name===((A=d==null?void 0:d.customCardPreferences)==null?void 0:A.componentName)}),v=n.resolveMultiInputType(d,x)==="multiple"&&!!((b=d==null?void 0:d.customCardPreferences)!=null&&b.url),f=!u||v,m=u||v;return!f&&!m?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[f&&s&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-border px-4",children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60",children:e.jsx(Zn,{mode:"config"})})}),f&&e.jsxs("button",{type:"button",onClick:()=>a(w=>!w),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Chart settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",s&&"rotate-180"),strokeWidth:1.75})]}),m&&r&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Wn,{})}),m&&e.jsxs("button",{type:"button",onClick:()=>l(w=>!w),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",f&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]})]})}function $o({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:l}=r,u=(l==null?void 0:l.joins)||[];if(u.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(i=>{var f,m,g,y;const x=`${(f=i.source)==null?void 0:f.entityName}.${(m=i.source)==null?void 0:m.name}`,h=`${(g=i.target)==null?void 0:g.entityName}.${(y=i.target)==null?void 0:y.name}`,v=i.operator||"=";return`${x} ${v} ${h}`}).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((i,x)=>({id:x,operator:i.operator,condition:c(i.keys)}));return e.jsx(n.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(qa,{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(n.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:u.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:u.map((d,i)=>{const x=o(d),h=Array.isArray(x);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(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(n.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:h?x.map(v=>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:v.condition}),v.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",v.operator,")"]})]},v.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:x})})})]},d.id||i)})})})]})})]}),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(n.SquarePen,{className:"size-3.5"})})]})})}function Ko({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:l,groupByFields:u,pivotByFields:c,metricsFields:o,sortByFields:d,detailFields:i,activeField:x}){var T,N;const[h,v]=C.useState(!1),f=t.useEditorStore(M=>M.card),m=t.useEditorStore(M=>M.editorContext),g=t.useEditorStore(M=>M.actions.updateCardConfig),y=(m==null?void 0:m.type)==="documentSection",{autoJoinMetadata:b}=n.useEditorCardQuery(f),w=((T=f==null?void 0:f.config)==null?void 0:T.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),A=((N=f==null?void 0:f.dataSource)==null?void 0:N.selectedEntities)||[],B=M=>{g(f.id,{...f==null?void 0:f.config,joinPlan:M}),v(!1)},S=()=>{g(f.id,{...f==null?void 0:f.config,joinPlan:void 0}),v(!1)},E=()=>{v(!1)},I=()=>{v(!0)};return r?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!y&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Tr,{selectedChart:s,onChartChange:a})}),l&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:l,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx($o,{onEditJoins:I})}),e.jsx(_o,{groupByFields:u,pivotByFields:c,metricsFields:o,sortByFields:d,detailFields:i,activeField:x})]}),e.jsx(qo,{}),e.jsx(On,{open:h,onOpenChange:v,joinPlan:w,availableDataSources:A,onSave:B,onCancel:E,onRemove:S,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:l&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:l,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function Go({initialFilters:s,availableFields:a}={}){const[r,l]=C.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:u,isLoading:c}=n.useFilterableFields(),o=a||u||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},i=S=>{const E=I=>{if(I.id===S){const T=o[0]||d,N=t.getDataType(T.dataType)==="date";return{...I,conditions:[...I.conditions,{id:`condition-${Date.now()}`,field:T,operator:N?"between":"=",value:N?[]:""}]}}return{...I,groups:I.groups.map(E)}};l(E(r))},x=S=>{const E=I=>{if(I.id===S){const T=o[0]||d,N=t.getDataType(T.dataType)==="date";return{...I,groups:[...I.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...I,groups:I.groups.map(E)}};l(E(r))},h=(S,E)=>{const I=T=>T.id===S?{...T,conditions:T.conditions.filter(N=>N.id!==E)}:{...T,groups:T.groups.map(I)};l(I(r))},v=(S,E)=>{const I=T=>T.id===S?{...T,groups:T.groups.filter(N=>N.id!==E)}:{...T,groups:T.groups.map(I)};l(I(r))},f=(S,E,I,T)=>{if(I==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=M=>M.id===S?{...M,conditions:M.conditions.map(j=>j.id===E?{...j,[I]:T}:j)}:{...M,groups:M.groups.map(N)};l(N(r))},m=(S,E,I)=>{const T=N=>N.id===S?{...N,conditions:N.conditions.map(M=>M.id===E?{...M,...I}:M)}:{...N,groups:N.groups.map(T)};l(T(r))},g=(S,E)=>{const I=T=>T.id===S?{...T,logicalOperator:E}:{...T,groups:T.groups.map(I)};l(I(r))},y=(S,E)=>{const I=T=>T.id===S?{...T,negate:E}:{...T,groups:T.groups.map(I)};l(I(r))},b=(S,E,I)=>{const T=N=>N.id===S?{...N,conditions:n.arrayMove(N.conditions,E,I)}:{...N,groups:N.groups.map(T)};l(T(r))},w=(S,E,I)=>{const T=N=>N.id===S?{...N,groups:n.arrayMove(N.groups,E,I)}:{...N,groups:N.groups.map(T)};l(T(r))},A=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const E=T=>{let N="";typeof T.field=="object"?N=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:N=String(T.field);const M=T.operator;let j=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(T.field.dataType==="date"||T.field.dataType==="datetime"||T.field.dataType==="timestamp")if(T.operator==="between"&&Array.isArray(j)&&j.length===2){const O=j[0]?`'${j[0]}'`:"NULL",D=j[1]?`'${j[1]}'`:"NULL";return`${N} BETWEEN ${O} AND ${D}`}else if((T.operator==="in"||T.operator==="not in")&&Array.isArray(j)){const O=j.map(D=>D?`'${D}'`:"NULL").join(", ");return`${N} ${M} (${O})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(T.operator)){let O=[];Array.isArray(j)?O=j.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof j=="string"?O=j.split(",").map(D=>{const L=D.trim();return T.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(O=[String(j)]),j=`(${O.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${N} LIKE '%${j.replace(/'/g,"")}'`:`${N} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${N} LIKE '${j.replace(/'/g,"")}%'`:`${N} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${N} LIKE '%${j.replace(/'/g,"")}'`:`${N} LIKE '%${String(j)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${M} ${j}`}},I=T=>{const N=T.conditions.map(E),M=T.groups.map(L=>I(L)),j=[...N,...M].filter(Boolean);if(j.length===0)return"";const O=j.join(` ${T.logicalOperator} `),D=j.length>1?`(${O})`:O;return T.negate?`NOT ${D}`:D};return I(S)},B=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:l,availableFields:o,isLoading:c,addCondition:i,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:f,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:y,reorderConditions:b,reorderGroups:w,generateSQLPreview:A,hasAnyFilters:B}}function Uo({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Ho=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Qo({value:s,onValueChange:a,availableFields:r,placeholder:l="Select field",className:u="w-64"}){const[c,o]=C.useState(!1),d=C.useMemo(()=>{const i={};return r.forEach(x=>{const h=Ho(x);i[h]||(i[h]={}),i[h][x.entityId]||(i[h][x.entityId]=[]),i[h][x.entityId].push(x)}),i},[r]);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",u),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Uo,{children:[s.entityName,".",s.name]})}):l,e.jsx(n.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(n.CommandEmpty,{children:"No fields found."}),e.jsx(n.CommandList,{className:"max-h-80",children:Object.entries(d).map(([i,x])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),i]}),children:Object.entries(x).map(([h,v])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[n.getEntityIcon(v[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:v[0].entityName})]}),v.map((f,m)=>e.jsxs(n.CommandItem,{value:f.id,onSelect:()=>{a(f),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)===f.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:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+m))]},`${i}-${h}`))},i))})]})})]})}function ys(s){var y;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:l}=n.useSemaphorContext(),u=t.useEditorStore(b=>b.card.config),c=u==null?void 0:u.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[o],metricColumns:[d],sortByColumns:[i]},h=((y=a.dataSource)==null?void 0:y.connectionId)||a.connectionId,{data:v,isPending:f,error:m}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:h,cardConfig:x,cardDataSource:a.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((v==null?void 0:v.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:f,error:m}}function Wo({field:s,selected:a,onChange:r,placeholder:l="Select items...",className:u}){const[c,o]=zt.useState(!1),{filterValues:d}=ys(s),i=h=>{r(a.filter(v=>v!==h))},x=h=>{a.includes(h)?r(a.filter(v=>v!==h)):r([...a,h])};return e.jsx("div",{className:t.cn("w-full",u),children:e.jsxs(t.Popover,{open: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:a.length>0?a.map(h=>{const v=d.find(f=>f.value===h);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[v==null?void 0:v.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&i(h)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),i(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:l})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No results found."}),e.jsx(n.CommandGroup,{children:d.map((h,v)=>e.jsxs(n.CommandItem,{onSelect:()=>x(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+v))})]})]})})]})})}function Jo({field:s,value:a,onChange:r,placeholder:l="Select value...",className:u}){const{filterValues:c,isPending:o,error:d}=ys(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:u||"flex-1",children:e.jsx(t.SelectValue,{placeholder:l,children:a})}),e.jsx(t.SelectContent,{children:c.map((i,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:i.value,children:i.label},i.value+x))})]})}function Yo({value:s,operator:a,onChange:r,className:l}){var m,g,y;const{tokenProps:u}=n.useSemaphorContext(),c=((g=(m=u==null?void 0:u.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((y=u==null?void 0:u.params)==null?void 0:y.timezone),o=c||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",i=C.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,w=s[1]?new Date(s[1]):void 0;if(b&&w)return{from:b,to:w}}},[s,d]),x=C.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const w=new Date(b);if(!isNaN(w.getTime()))return w},[s,d]),h=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,o):t.startOfDayInTimezone(b,o),v=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},f=b=>{if(!b){r("");return}const w=h(b);r(w.toISOString())};return e.jsx(n.DateRangePicker,{value:d?i:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:x,onChange:v,onSingleChange:f,timezone:c,showRelativeTab:d,className:l,placeholder:"Select date..."})}const Xo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Zo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ei=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ti=["=","!=","isNull","isNotNull"],si=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],ni={"=":"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 Dn(s){return ni[s]||t.titleCase(s)}function ai(s){switch(s){case"string":return Zo;case"number":return ei;case"boolean":return ti;case"date":return si;default:return Xo}}function ta({condition:s,index:a,groupId:r,groupLogicalOperator:l,onUpdateCondition:u,onRemoveCondition:c,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:i}){const{attributes:x,listeners:h,setNodeRef:v,transform:f,transition:m,isDragging:g}=n.useSortable({id:s.id}),{isPending:y,error:b}=ys(s.field),w={transform:n.CSS.Transform.toString(f),transition:m};return e.jsxs("div",{ref:v,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",{...x,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:l,onValueChange:A=>o(r,A),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Qo,{value:s.field,onValueChange:A=>{const B=A,S=t.getDataType(B.dataType)==="date";i(r,s.id,{field:B,value:"",operator:S?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:A=>{A==="in"||A==="not in"?i(r,s.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?i(r,s.id,{operator:A,value:null}):A==="between"||A==="not between"?i(r,s.id,{operator:A,value:[]}):i(r,s.id,{operator:A,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Dn(s.operator):""})}),e.jsx(t.SelectContent,{children:ai(t.getDataType(s.field.dataType)).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A,children:Dn(A)},A))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?y?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Wo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(A=>typeof A=="string")?s.value:[],onChange:A=>i(r,s.id,{value:A}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:A=>i(r,s.id,{value:A.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Jo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:A=>i(r,s.id,{value:A}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:A=>i(r,s.id,{value:A==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Yo,{value:s.value,operator:s.operator,onChange:A=>i(r,s.id,{value:A}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:A=>u(r,s.id,"value",A.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>c(r,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function ri({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:l,onUpdateGroupNegate:u,onRemoveGroup:c,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:i,onReorderConditions:x,onReorderGroups:h,onAddCondition:v,onAddGroup:f,availableFields:m,renderFilterGroup:g,updateConditionFields:y}){const{attributes:b,listeners:w,setNodeRef:A,transform:B,transition:S,isDragging:E}=n.useSortable({id:s.id}),I={transform:n.CSS.Transform.toString(B),transition:S},T=M=>{const{active:j,over:O}=M;if(O&&j.id!==O.id){const D=s.conditions.findIndex(R=>R.id===j.id),L=s.conditions.findIndex(R=>R.id===O.id);D!==-1&&L!==-1&&x(s.id,D,L)}},N=M=>{const{active:j,over:O}=M;if(O&&j.id!==O.id&&r){const D=s.groups.findIndex(R=>R.id===j.id),L=s.groups.findIndex(R=>R.id===O.id);D!==-1&&L!==-1&&h(r,D,L)}};return e.jsxs("div",{ref:A,style:I,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...w,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>u(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:M=>l(s.id,M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>r&&c(r,s.id),children:e.jsx(n.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:T,children:e.jsx(n.SortableContext,{items:s.conditions.map(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((M,j)=>e.jsx(ta,{condition:M,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:m,updateConditionFields:y},M.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:N,children:e.jsx(n.SortableContext,{items:s.groups.map(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(M=>g(M,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>v(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function li({filters:s,availableFields:a,onSave:r,onClearAll:l,onCancel:u}){const{currentFilters:c,availableFields:o,isLoading:d,addCondition:i,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:f,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:y,reorderConditions:b,reorderGroups:w,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:S}=Go({initialFilters:s,availableFields:a}),E=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[I,T]=C.useState(!1),N=(O,D,L)=>{const R=p=>p.id===O?{...p,conditions:p.conditions.map(F=>F.id===D?{...F,field:L,dataType:L.dataType}:F)}:{...p,groups:p.groups.map(R)};S(R(c))},M=(O,D=0,L)=>D===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:p,over:F}=R;if(F&&p.id!==F.id){const k=O.conditions.findIndex(V=>V.id===p.id),P=O.conditions.findIndex(V=>V.id===F.id);k!==-1&&P!==-1&&b(O.id,k,P)}},children:e.jsx(n.SortableContext,{items:O.conditions.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:O.conditions.map((R,p)=>e.jsx(ta,{condition:R,index:p,groupId:O.id,groupLogicalOperator:O.logicalOperator,onUpdateCondition:f,onUpdateField:N,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:m},R.id))})}),e.jsx(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:p,over:F}=R;if(F&&p.id!==F.id){const k=O.groups.findIndex(V=>V.id===p.id),P=O.groups.findIndex(V=>V.id===F.id);k!==-1&&P!==-1&&w(O.id,k,P)}},children:e.jsx(n.SortableContext,{items:O.groups.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:O.groups.map(R=>M(R,D+1,O.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:()=>i(O.id),children:[e.jsx(n.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:()=>x(O.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},O.id):e.jsx(ri,{group:O,depth:D,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:y,onRemoveGroup:v,onUpdateCondition:f,onUpdateField:N,onRemoveCondition:h,onReorderConditions:b,onReorderGroups:w,onAddCondition:i,onAddGroup:x,availableFields:o,renderFilterGroup:M,updateConditionFields:m},O.id),j=n.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(n.Card,{children:e.jsx(n.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):M(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.Switch,{size:"sm",id:"advanced-mode",checked:I,onCheckedChange:O=>T(O)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:A(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:u,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:l,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(B?c:null),children:"Apply Filters"})]})]})}function oi({cardId:s,filters:a,onFiltersChange:r,onClearFilters:l,availableFields:u,isOpen:c,onOpenChange:o}){const d=x=>{r(s,x),o(!1)},i=()=>{l(s),o(!1)};return e.jsxs(n.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(n.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Card Filters"}),e.jsx(n.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(li,{filters:a,availableFields:u,onSave:d,onCancel:()=>o(!1),onClearAll:i})]})]})}function ii({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:l}){var A,B;const[u,c]=C.useState(null),o=t.useEditorStore(S=>S.card),d=t.useEditorStore(S=>S.actions.updateCardConfig),i=t.useEditorStore(S=>S.actions.setCardPreferences),x=(A=o==null?void 0:o.config)==null?void 0:A.joinPlan,h=C.useCallback(S=>S.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),v=(B=o==null?void 0:o.dataSource)==null?void 0:B.semanticDomainId,{data:f}=n.useJoinabilityMap(v),m=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],g=C.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(E=>E.id===S)?"source":r("groupBy").find(E=>E.id===S)?"groupBy":r("metrics").find(E=>E.id===S)?"metrics":r("pivotBy").find(E=>E.id===S)?"pivotBy":r("sortBy").find(E=>E.id===S)?"sortBy":r("detailColumns").find(E=>E.id===S)?"detailColumns":null,[a,r]),y=C.useCallback(S=>{c(S.active.id)},[]),b=C.useCallback(S=>{var O;const{active:E,over:I}=S;if(!I||!s){c(null);return}const T=E.id,N=I.id,M=g(T),j=g(N)||N;if(j==="sortBy"){if(M==="source"){const D=a.find(R=>R.id===T);if(!D){c(null);return}if(!(r("groupBy").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName)||r("metrics").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName)||r("detailColumns").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName))){c(null);return}}else if(M==="pivotBy"){c(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){c(null);return}}if(M==="source"&&j==="sortBy"){const D=[...a].find(F=>F.id===T);if(!D){c(null);return}const L=r("sortBy");if(n.fieldAlreadyExists(D,L)){c(null);return}const R=n.validateFieldForChartType(D,"sortBy",o.type);if(!R.isValid){n.ue.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3}),c(null);return}const p=n.getNewField(D,"sortBy",L);c(null),l("sortBy",[...L,p]);return}if(M==="source"&&j!=="source"&&j!=="sortBy"){const D=[...a].find(V=>V.id===T);if(!D){c(null);return}const L=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],R=L.filter(V=>!h(V));if(R.length>0){const V=R[0].qualifiedEntityName;if(!V){c(null);return}if(V!==D.qualifiedEntityName&&!h(D)&&D.qualifiedEntityName)if(v&&(f!=null&&f.joinabilityMap)){if(n.calculateFieldState(D,{joinabilityMap:f.joinabilityMap,selectedFields:L,baseEntityName:(O=x==null?void 0:x.baseEntity)==null?void 0:O.name}).state==="unreachable"){n.showJoinRequiredNotification(),c(null);return}}else{if(!x){n.showJoinRequiredNotification(),c(null);return}if(!n.areEntitiesJoined(V,D.qualifiedEntityName,x)){n.showJoinRequiredNotification(),c(null);return}}}const p=r(j);if(n.fieldAlreadyExists(D,p)){c(null);return}const F=n.validateFieldForChartType(D,j,o.type);if(!F.isValid){n.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const k=n.getNewField(D,j,p),P=[...p,k];if(c(null),l(j,P),j==="metrics"&&s){const V=n.seedSemanticMetricFormatDefaults(o,k,o.preferences);V&&i(V),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(M&&j&&M!=="source"&&j!=="source"&&M!==j){const D=r(M),L=r(j),R=D.find(V=>V.id===T);if(!R){c(null);return}const p=n.validateFieldForChartType(R,j,o.type);if(!p.isValid){n.ue.error("Invalid Field Type",{description:p.reason,position:"top-center",duration:3e3}),c(null);return}const F=n.getNewField(R,j,L);if(c(null),j==="sortBy"){n.fieldAlreadyExists(R,L)||l(j,[...L,F]);return}const k=D.filter(V=>V.id!==T),P=[...L,F];if(l(M,k),l(j,P),j==="metrics"&&s){const V=n.seedSemanticMetricFormatDefaults(o,F,o.preferences);V&&i(V),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(M&&j&&M===j&&M!=="source"){const D=r(M),L=D.findIndex(p=>p.id===T),R=D.findIndex(p=>p.id===N);if(L!==R){const p=n.arrayMove(D,L,R);l(M,p)}}c(null)},[s,a,r,l,g,x,v,f,h,o,d,i]),w=u?m.find(S=>S.id===u):null;return{activeId:u,activeField:w,handleDragStart:y,handleDragEnd:b}}function ci({activeView:s,onViewChange:a,splitViewEnabled:r}){const l=t.useEditorStore(i=>i.card),{config:u}=C.useContext(n.SemaphorContext).tokenProps,c=(u==null?void 0:u.showInfoTab)!==!1,o=()=>r?!1:t.getVisualizationMode(l)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(l.type),d=[{id:"chart",label:"Chart"}];return o()&&d.push({id:"table",label:"Results"}),l.type!=="kpi"&&c&&d.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:i=>a(i),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:d.map(i=>{const x=i.icon;return e.jsxs(t.TabsTrigger,{value:i.id,className:"gap-1.5 px-0 text-[13px]",children:[x&&e.jsx(x,{className:"h-3 w-3",strokeWidth:1.75}),i.label]},i.id)})})})}const di=[{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 ui(){var i,x;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[r,l]=C.useState(!1),[u,c]=C.useState(""),o=h=>{if(h==="custom"){l(!0);return}l(!1),a(s.id,parseInt(h))},d=h=>{const v=h.target.value;c(v),v&&!isNaN(parseInt(v))&&a(s.id,parseInt(v))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:u,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(i=s.config)==null?void 0:i.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(n.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:di.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function mi({card:s,queryData:a,isLoading:r,isFetching:l,pagination:u,onPaginationChange:c,onSortChange:o,sortState:d,splitViewEnabled:i,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:h}){const v=C.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),f=t.getVisualizationMode(s)==="dynamic",m=e.jsx(it,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Un,{fallbackPreview:e.jsx(it,{}),records:v,title:s.title,isInspectorOpen:x,onInspectorOpenChange:h})});return f?i?e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(r||l)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:v,paginationMetadata:u,onPaginationChange:c,isLoading:r||l,onSortChange:o,sortState:d})]})})]}):m:!i||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(it,{}):e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(it,{})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(r||l)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:v,paginationMetadata:u,onPaginationChange:c,isLoading:r||l,onSortChange:o,sortState:d})]})})]})}function xi(s,a){const[r,l]=C.useState(()=>{const u=localStorage.getItem(s);return u?JSON.parse(u):a});return C.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,l]}const hi="semaphor-split-view-enabled";function pi(){return xi(hi,!0)}function fi({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:l,columns:u}){var Z,je,Ie;const c=t.useEditorStore(ne=>ne.card),o=t.useEditorStore(ne=>ne.editorContext),d=t.useEditorStore(ne=>ne.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),i=t.useEditorStore(ne=>ne.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ne=>ne.filterValues),h=t.useDashboardStore(ne=>ne.selectedSheetId),{updateCardConfig:v,setCard:f,updateCardInFrame:m,setShowAIDialog:g}=t.useEditorActions(),y=t.useEditorStore(ne=>ne.showAIDialog),b=t.useEditorStore(ne=>ne.isDevMode),w=t.useDashboardStore(ne=>ne.isVisualEditing),[A,B]=C.useState(!1),[S,E]=C.useState(!1),[I,T]=C.useState(!1),[N,M]=C.useState(null),{config:j}=C.useContext(n.SemaphorContext).tokenProps,O=(j==null?void 0:j.showInfoTab)!==!1,D=(j==null?void 0:j.showQueryDebugTools)!==!1,[L,R]=pi();t.useEditorStore(ne=>{var Ae;return!!((Ae=ne.card.customCardPreferences)!=null&&Ae.url)});const F=t.getVisualizationMode(c)==="dynamic",k=(o==null?void 0:o.type)==="documentSection",{data:P,errorMessage:V,isLoading:z,isFetching:_,errorSql:q,pagination:W,refetch:$,comparisonMetadata:U,queryRequestPayload:se,resolvedPrimaryDateField:ie}=n.useEditorCardQuery(l),le=C.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[de,me]=C.useState(!1);C.useEffect(()=>{_||me(!1)},[_]);const ue=()=>{const ne=!L;ne&&s==="table"&&a("chart"),R(ne)},Ne=(ne,Ae)=>{const Le={...l,paginationConfig:{page:ne+1,pageSize:Ae}};f(Le),m(Le)},we=ne=>{if(!c.config)return;const Ae=n.sortStateToSortByColumns(ne,c.config.metricColumns,c.config.groupByColumns,c.config.detailColumns);v(c.id,{...c.config,sortByColumns:Ae})},Te=C.useMemo(()=>{var ne;return n.sortByColumnsToSortState((ne=c.config)==null?void 0:ne.sortByColumns)},[(Z=c.config)==null?void 0:Z.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":y&&w}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&y&&!k&&!F&&e.jsx("div",{className:"w-[200px]",children:e.jsx(wr,{variant:b?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(ci,{activeView:s,onViewChange:a,splitViewEnabled:L}),e.jsx(ui,{})]}),U&&c.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),y&&e.jsx(Me.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:l.id,cardFilters:(je=l.config)==null?void 0:je.filters,cardFilterCount:n.getFilterCount(((Ie=l.config)==null?void 0:Ie.filters)||null),onFiltersClick:r,inlineFilters:l.inlineFilters,inlineFilterValues:d,sheetId:h||"",removeInlineFilterValue:ne=>i(l.id,ne),resolvedPrimaryDateField:ie}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:z||_,onClick:()=>{me(!0),$()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":de})})}),s==="chart"&&!F&&e.jsx(Gn,{showInlineFilters:!1,showDisplayOptions:!1}),s==="chart"&&e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"More Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:ue,children:[L?e.jsx(Ta,{className:"mr-2 h-4 w-4"}):e.jsx(Va,{className:"mr-2 h-4 w-4"}),L?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(gs,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Hn,{onCustomize:()=>T(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col",children:e.jsx(mi,{card:l,queryData:P,isLoading:z,isFetching:_,pagination:W,onPaginationChange:Ne,onSortChange:we,sortState:Te,splitViewEnabled:L,isDynamicInspectorOpen:I,onDynamicInspectorOpenChange:T})}),s==="table"&&(P==null?void 0:P.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(z||_)&&(P==null?void 0:P.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(n.TableVisual,{card:l,data:le,comparisonMetadata:U,paginationMetadata:W,onPaginationChange:Ne,isLoading:z||_,onSortChange:we,sortState:Te})]}),s==="info"&&O&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-4",children:V?e.jsx(ps,{error:V,errorSql:q,onSendFeedback:()=>{const ne=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:c.config,dataSource:l.dataSource,dashboardFilters:x,errorMessage:V,errorSql:q,generatedSql:P==null?void 0:P.sql});M(ne),E(!0)},onOpenInEditor:()=>{g(!0),setTimeout(()=>{const ne=t.useEditorStore.getState().actions;ne.setIsDevMode(!0),ne.setCardSql(q||""),setTimeout(()=>{ne.setRunSql(!0)},100)},100)}}):(P==null?void 0:P.sql)&&e.jsx(Qn,{sql:P.sql,showCardDetails:!0,debugPayloads:D?{queryRequest:se,queryResponse:P,columns:u,dashboardFilters:x}:void 0})})})]}),N&&e.jsx(n.FeedbackDialog,{open:S,onOpenChange:E,feedbackData:N})]})})}function gi({activeField:s}){const[a,r]=C.useState(!0);if(C.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const l=!!n.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(n.TypeGlyph,{dataType:s.dataType,calculated:l}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const bi=()=>{const s=console.error;console.error=(...l)=>{l.length>0&&typeof l[0]=="string"&&l[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,l)};const a=l=>{if(l.message&&(l.message.includes("ResizeObserver loop completed with undelivered notifications")||l.message.includes("ResizeObserver loop limit exceeded")))return l.preventDefault(),l.stopPropagation(),!1},r=l=>{var u;if((u=l.reason)!=null&&u.message&&(l.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||l.reason.message.includes("ResizeObserver loop limit exceeded")))return l.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",r,!0)}};function ji({column:s,isSelected:a,onSelect:r,availableFields:l,width:u,onWidthChange:c}){var V,z,_;const o=t.useEditorStore(q=>q.card),{updateCardConfig:d,removeGroupByColumn:i,removeMetricColumn:x,updateFilters:h}=t.useEditorActions(),[v,f]=C.useState(!1),[m,g]=C.useState(!1),y=C.useRef(null),b=C.useCallback(q=>{q.preventDefault(),q.stopPropagation(),g(!0),y.current={startX:q.clientX,startWidth:u||150};const W=U=>{if(!y.current)return;const se=U.clientX-y.current.startX,ie=Math.max(80,y.current.startWidth+se);c==null||c(s.id,ie)},$=()=>{g(!1),y.current=null,document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",$)};document.addEventListener("mousemove",W),document.addEventListener("mouseup",$)},[u,s.id,c]),w=(V=o==null?void 0:o.config)==null?void 0:V.filters,A=(z=w==null?void 0:w.conditions)==null?void 0:z.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),B=q=>{q?h(o.id,q):d(o.id,{filters:void 0})},{attributes:S,listeners:E,setNodeRef:I,transform:T,transition:N,isDragging:M}=n.useSortable({id:s.id}),j={transform:n.CSS.Transform.toString(T),transition:N},O=t.getDataType(s.dataType),D=vi(O),L=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.sortByColumns)||[],W=q.findIndex(U=>U.name===s.name);if(W!==-1){const U=[...q];U[W]={...U[W],direction:"asc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.sortByColumns)||[],W=q.findIndex(U=>U.name===s.name);if(W!==-1){const U=[...q];U[W]={...U[W],direction:"desc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},p=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.groupByColumns)||[];if(!q.some(U=>U.name===s.name)){const U={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...q,U]})}},F=q=>{var U;const W=((U=o==null?void 0:o.config)==null?void 0:U.metricColumns)||[];if(!W.some(se=>se.name===s.name&&se.aggregate===q)){const se={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q};d(o.id,{metricColumns:[...W,se]})}},k=()=>{s.role==="groupby"?i(o.id,s.id):s.role==="metric"&&x(o.id,s.id)},P={...j,width:u?`${u}px`:void 0,minWidth:u?`${u}px`:"120px"};return e.jsxs("th",{ref:I,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...E,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:r,className:t.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(D,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),A&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>f(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:L,children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:R,children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(n.DropdownMenuSubContent,{children:[e.jsx(n.DropdownMenuItem,{onClick:()=>F("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:p,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(hs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(n.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(n.DropdownMenuItem,{onClick:k,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(ea,{open:v,onOpenChange:f,availableFields:l.length>0?l:[s],existingFilters:w,editingCondition:A?(_=w==null?void 0:w.conditions)==null?void 0:_.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function vi(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function yi({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:l=[],filterableFields:u=l}){var M,j,O,D;const c=t.useEditorStore(L=>L.card),{updateCardConfig:o}=t.useEditorActions(),[d,i]=C.useState(null),[x,h]=C.useState({}),[v,f]=C.useState(!1),m=C.useMemo(()=>{var p,F;const L=((p=c==null?void 0:c.config)==null?void 0:p.groupByColumns)||[],R=((F=c==null?void 0:c.config)==null?void 0:F.metricColumns)||[];return[...L,...R]},[(M=c==null?void 0:c.config)==null?void 0:M.groupByColumns,(j=c==null?void 0:c.config)==null?void 0:j.metricColumns]),g=C.useMemo(()=>{const L=new Set(m.map(R=>`${R.qualifiedEntityName}.${R.name}`));return l.filter(R=>!L.has(`${R.qualifiedEntityName}.${R.name}`))},[l,m]),{data:y,isLoading:b}=n.useEditorCardQuery(c),w=(y==null?void 0:y.records)||[],A=C.useCallback((L,R)=>{h(p=>({...p,[L]:R}))},[]),B=C.useCallback(L=>{var k,P;const R=t.getDataType(L.dataType),p=((k=c==null?void 0:c.config)==null?void 0:k.groupByColumns)||[],F=((P=c==null?void 0:c.config)==null?void 0:P.metricColumns)||[];if(R==="number"){const V={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(c.id,{metricColumns:[...F,V]})}else{const V={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};o(c.id,{groupByColumns:[...p,V]})}f(!1)},[(O=c==null?void 0:c.config)==null?void 0:O.groupByColumns,(D=c==null?void 0:c.config)==null?void 0:D.metricColumns,c.id,o]),S=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),E=L=>{i(L.active.id)},I=L=>{const{active:R,over:p}=L;if(i(null),!p||R.id===p.id)return;const F=m.findIndex(P=>P.id===R.id),k=m.findIndex(P=>P.id===p.id);if(F!==-1&&k!==-1){const P=n.arrayMove(m,F,k),V=P.filter(_=>_.role==="groupby"),z=P.filter(_=>_.role==="metric");o(c.id,{groupByColumns:V,metricColumns:z})}},T=d?m.find(L=>L.id===d):null,N=L=>{let R="";for(;L>=0;)R=String.fromCharCode(L%26+65)+R,L=Math.floor(L/26)-1;return R};return r?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"})}):m.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragStart:E,onDragEnd:I,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(n.SortableContext,{items:m.map(L=>L.id),strategy:n.horizontalListSortingStrategy,children:m.map((L,R)=>e.jsx("th",{style:{width:x[L.id]?`${x[L.id]}px`:void 0,minWidth:x[L.id]?`${x[L.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:N(R)},`letter-${L.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(n.SortableContext,{items:m.map(L=>L.id),strategy:n.horizontalListSortingStrategy,children:m.map(L=>e.jsx(ji,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>a(L),availableFields:u,width:x[L.id],onWidthChange:A},L.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:v,onOpenChange:f,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(n.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns available."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:g.map(L=>{const R=t.getDataType(L.dataType),p=R==="number"?n.Hash:R==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:L.label||L.name,onSelect:()=>B(L),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:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.entityName})]})]},L.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):w.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):w.slice(0,100).map((L,R)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",R%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:R+1}),m.map(p=>{const F=L[p.name]??L[p.label??""];return e.jsx("td",{style:{width:x[p.id]?`${x[p.id]}px`:void 0,minWidth:x[p.id]?`${x[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:Ni(F,p)})},`${R}-${p.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(n.DragOverlay,{children:T&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:T.label||T.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(w.length,100)," of ",w.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function Ni(s,a){if(s==null)return"—";if(typeof s=="number")return a.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Ci({entityGroups:s,isLoading:a=!1}){var B,S;const r=t.useEditorStore(E=>E.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:c}=t.useEditorActions(),[o,d]=C.useState(!0),[i,x]=C.useState(""),[h,v]=C.useState(new Set),f=((B=r==null?void 0:r.config)==null?void 0:B.groupByColumns)||[],m=((S=r==null?void 0:r.config)==null?void 0:S.metricColumns)||[],g=E=>{const I=new Set(h);I.has(E)?I.delete(E):I.add(E),v(I)},y=E=>f.some(I=>I.name===E.name&&I.qualifiedEntityName===E.qualifiedEntityName)||m.some(I=>I.name===E.name&&I.qualifiedEntityName===E.qualifiedEntityName),b=(E,I)=>{if(I)if(t.getDataType(E.dataType)==="number"){const N={...E,id:`metric-${E.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(r.id,{metricColumns:[...m,N]})}else{const N={...E,id:`groupby-${E.id}-${Date.now()}`,role:"groupby"};l(r.id,{groupByColumns:[...f,N]})}else{const T=f.findIndex(M=>M.name===E.name&&M.qualifiedEntityName===E.qualifiedEntityName),N=m.findIndex(M=>M.name===E.name&&M.qualifiedEntityName===E.qualifiedEntityName);T!==-1&&u(r.id,f[T].id),N!==-1&&c(r.id,m[N].id)}},w=E=>{if(!i)return E;const I=i.toLowerCase();return E.filter(T=>T.name.toLowerCase().includes(I)||T.label&&T.label.toLowerCase().includes(I))},A=E=>{switch(t.getDataType(E)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(Ma,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(n.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:i,onChange:E=>x(E.target.value),className:"h-8 pl-8 text-sm"})]})}),(f.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[f.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx($t,{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:f.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:f.map(E=>{const I=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>u(r.id,E.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},E.id)})})})]}),m.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:m.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(E=>{const I=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:E.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(r.id,E.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},E.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(E=>{const I=w(E.columns);if(I.length===0)return null;const T=h.has(E.entityId)||i.length>0;return e.jsxs(n.Collapsible,{open:T,onOpenChange:()=>g(E.entityId),children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",T&&"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:E.label||E.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:I.map(N=>{const M=A(N.dataType),j=y(N);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",j&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:j,onCheckedChange:O=>b(N,O),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:N.label||N.name})]},N.id)})})})]},E.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(La,{className:"h-4 w-4"})})})}const Si=[{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 wi({value:s,onChange:a,onSubmit:r,onCancel:l,selectedColumn:u,availableColumns:c}){const[o,d]=C.useState(!1),[i,x]=C.useState("column"),h=C.useRef(null);C.useEffect(()=>{const g=y=>{y.key==="Escape"&&s?l():y.key==="Enter"&&s&&!o&&r(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,l,r,o]);const v=g=>{const y=`[${g.label||g.name}]`,b=h.current;if(b){const w=b.selectionStart||0,A=b.selectionEnd||0,B=s.slice(0,w)+y+s.slice(A);a(B),setTimeout(()=>{b.setSelectionRange(w+y.length,w+y.length),b.focus()},0)}else a(s+y);d(!1)},f=g=>{const y=h.current;if(y){const b=y.selectionStart||0,w=y.selectionEnd||0,A=s.slice(0,b)+g.syntax+s.slice(w);a(A),setTimeout(()=>{y.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),y.focus()},0)}else a(s+g.syntax);d(!1)},m=g=>{switch(t.getDataType(g)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:u?e.jsx("span",{className:"truncate",children:u.label||u.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&i==="function",onOpenChange:g=>{d(g),g&&x("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Ba,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search functions..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No functions found."}),e.jsx(n.CommandGroup,{heading:"Functions",children:Si.map(g=>e.jsx(n.CommandItem,{value:g.name,onSelect:()=>f(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&&i==="column",onOpenChange:g=>{d(g),g&&x("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns found."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:c.map(g=>{const y=m(g.dataType);return e.jsxs(n.CommandItem,{value:g.label||g.name,onSelect:()=>v(g),children:[e.jsx(y,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:h,value:s,onChange:g=>a(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:l,title:"Cancel (Esc)",children:e.jsx(t.X,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>r(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function Ti({className:s}){var m,g,y,b;const a=t.useEditorStore(w=>w.card),[r,l]=C.useState(null),[u,c]=C.useState(""),{columns:o=[],columnGroups:d=[],isLoading:i}=n.useColumns(),{valuePickFilterableFields:x=[]}=n.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(y=a==null?void 0:a.config)!=null&&y.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const h=w=>{l(w),c(w?`[${w.label||w.name}]`:"")},v=w=>{console.log("Formula submitted:",w),c(""),l(null)},f=()=>{c(""),l(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(wi,{value:u,onChange:c,onSubmit:v,onCancel:f,selectedColumn:r,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(yi,{selectedColumn:r,onColumnSelect:h,isLoading:i,sourceFields:o,filterableFields:x})}),e.jsx(Ci,{entityGroups:d,isLoading:i})]})]})}function Ei(){var V,z;const[s,a]=C.useState("chart"),[r,l]=C.useState(!1),[u,c]=C.useState(!0),[o,d]=C.useState(!0),i=t.useEditorStore(_=>_.showAIDialog),x=t.useDashboardStore(_=>_.isVisualEditing),{setCardType:h}=t.useEditorActions(),v=t.useEditorStore(_=>_.card.type);C.useEffect(()=>bi(),[]);const f=_=>{h(_)},m=t.useEditorStore(_=>_.frame),g=t.useEditorStore(_=>_.card);t.useEditorStore(_=>_.activeTabCardId),t.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:y,removeCard:b,updateCard:w,setActiveCard:A,updateFilters:B}=t.useEditorActions(),{columnFields:S=[],scopedFields:E=[],filterableFields:I=[]}=n.useFilterableFields(),T=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),N=g,{getFieldsForContainer:M,setFieldsForContainer:j}=n.useFieldManagement(N),{activeField:O,handleDragStart:D,handleDragEnd:L}=ii({activeCardId:m.activeCardId,sourceFields:E,getFieldsForContainer:M,setFieldsForContainer:j}),R=(_,q)=>{q&&B(_,q)},p=_=>{var q;w(_,{config:{...(q=m.cards.find(W=>W.id===_))==null?void 0:q.config,filters:void 0}})},F=I,k=_=>{if(!_)return 0;let q=_.conditions.length;return _.groups.forEach(W=>{q+=k(W)}),q},P=k(((V=N==null?void 0:N.config)==null?void 0:V.filters)||null);return e.jsxs(n.DndContext,{sensors:T,collisionDetection:n.closestCenter,onDragStart:D,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Pn,{isVisible:u,onToggleVisibility:()=>c(!u)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:v==="tableBuilder"?e.jsx(Ti,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!i&&e.jsx(Ko,{selectedChart:v,onChartChange:f,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:O,isVisible:o,onToggleVisibility:()=>d(!o)}),e.jsx(fi,{selectedChart:v,activeView:s,onViewChange:a,onFiltersClick:()=>l(!0),filterCount:P,activeCard:N,columns:S,getFieldsForContainer:M,cards:m.cards,activeCardId:m.activeCardId,addCard:y,setActiveCard:A})]})}),!u&&x&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(n.Database,{className:"h-4 w-4"})})})]}),N&&e.jsx(oi,{cardId:N.id,filters:((z=N.config)==null?void 0:z.filters)||null,onFiltersChange:R,onClearFilters:p,availableFields:F,isOpen:r,onOpenChange:l}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(gi,{activeField:O||null})})]})}function Ii({authToken:s,onSave:a,onClose:r}){const l=C.useRef(null),u=t.useEditorStore(T=>T.showAIDialog),c=t.useEditorStore(T=>T.isDevMode),o=n.useAssistantLayoutStore(T=>T.setFullscreen),d=n.useAssistantLayoutStore(T=>T.setPanelOpen),i=n.useAssistantLayoutStore(T=>T.setContainer),x=n.useAssistantPanel("editor"),h=n.useFullscreenAssistant(),v=n.useAssistantContainer("editor"),f=h==="editor",m=n.useDashboardAppearance(),g=C.useCallback(T=>{i("editor",T)},[i]),{setAuthToken:y}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:w,setOnClose:A}=t.useEditorActions(),{setActiveAssistantType:B}=t.useAIActions();C.useEffect(()=>{a&&w(a),r&&A(r)},[a,w,r,A]),C.useEffect(()=>{s&&s.accessToken&&y(s)},[s,y]),C.useEffect(()=>{var T,N;u?((T=l.current)==null||T.resize(40),d("editor",!0),B("editor")):((N=l.current)==null||N.resize(0),d("editor",!1),h==="editor"&&o(null),B(null))},[u,d,B,o,h]);function S(T){var N;T<1?(b(!1),d("editor",!1),h==="editor"&&o(null),B(null),(N=l.current)==null||N.resize(0)):(u||(b(!0),B("editor")),x.isOpen||d("editor",!0))}function E(){return e.jsxs(e.Fragment,{children:[e.jsx(Pn,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Co,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:S,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(In,{isFullscreen:f,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,className:t.cn("absolute inset-0",!f&&"pointer-events-none")})]})]})}function I(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ei,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:S,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(In,{isFullscreen:f,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,className:t.cn("absolute inset-0",!f&&"pointer-events-none")})]})}return e.jsx(n.ErrorBoundary,{FallbackComponent:n.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:E()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:I()})})}function ki(){t.useDashboardStore(m=>m.selectedCardId);const s=t.useDashboardStore(m=>m.selectedSheetId),a=t.useDashboardStore(m=>m.dashboard),{setIsVisualEditing:r,setSelectedSheetId:l}=t.useDashboardStore(m=>m.actions),u=t.useEditorStore(m=>m.editorContext),{clearEditorContext:c}=t.useEditorStore(m=>m.actions),o=n.useDashboardAppearance(),d=t.useDashboardStore(m=>m.isVisualEditing),i=t.useDashboardStore(m=>m.actions.updateFrame),x=t.useDashboardStore(m=>m.actions.updateDocumentSectionCard),h=n.useResolveExistingFrameSemanticExecutionPayload();async function v(m){var A,B,S;if((u==null?void 0:u.type)==="documentSection"){const E=n.getDocumentSectionEditorCard(m,u.cardId);if(!E){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(E)){n.ue.error("Document table sections support Table and Pivot Table");return}x(u.sheetId,u.sectionId,E,{calculatedFields:m.calculatedFields}),c(),r(!1);return}const g=s?(A=a==null?void 0:a.sheets)==null?void 0:A.some(E=>{var I;return E.id===s&&((I=E.frames)==null?void 0:I.some(T=>T.id===m.id))}):!1,y=(S=(B=a==null?void 0:a.sheets)==null?void 0:B.find(E=>{var I;return(I=E.frames)==null?void 0:I.some(T=>T.id===m.id)}))==null?void 0:S.id,b=g?s:y||null;if(!b)return;const w=n.findDashboardFrameById(a,m.id);try{const E=await h(m,{previousFrame:w});i(b,m,{semanticExecutionPayload:E}),s!==b&&l(b),r(!1)}catch(E){console.error("Failed to resolve semantic metadata on save:",E),n.ue.error(E instanceof Error?E.message:"Failed to resolve semantic metadata for this visual")}}function f(){c(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!d}),style:o.dashboardContainerStyle,children:e.jsx(Ii,{onSave:v,onClose:f})})}exports.default=ki;
181
+ `;o(x)}:void 0}}function zn({className:s,style:a,...r}){var Q,te,xe,pe,Fe;const l=t.useEditorStore(ee=>ee.card),u=n.useDashboardAppearance(),o=t.useEditorStore(ee=>ee.isDevMode)?!1:((Q=l.customCardPreferences)==null?void 0:Q.showCardHeader)??!0,d=((xe=(te=l.preferences)==null?void 0:te.displayOptions)==null?void 0:xe.showInlineFilterBar)??!0,i=t.useEditorStore(ee=>ee.frame),x=t.useEditorStore(ee=>ee.inlineFilterValuesMap[l.id]),h=t.useDashboardStore(ee=>ee.dashboard.filters),v=t.useDashboardStore(ee=>ee.selectedSheetId),[f,m]=C.useState(!1),{currentUser:g}=n.useCurrentUserInfo(),{tokenProps:y}=C.useContext(n.SemaphorContext),b=t.useEditorStore(ee=>ee.actions.setRunSql),w=t.useEditorStore(ee=>ee.actions.setCardInlineFilterValue),A=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),{updateFilter:B}=t.useDashboardActions(),S=h==null?void 0:h.find(ee=>ee.id===i.filterId),E=C.useMemo(()=>n.findCustomVisualConfigCard(i,l),[i,l]),{manifest:I}=n.useCustomVisual(((pe=E==null?void 0:E.customCardPreferences)==null?void 0:pe.url)||""),T=C.useMemo(()=>{var ee;return(ee=I==null?void 0:I.visuals)==null?void 0:ee.find(Se=>{var fe;return Se.name===((fe=E==null?void 0:E.customCardPreferences)==null?void 0:fe.componentName)})},[I,(Fe=E==null?void 0:E.customCardPreferences)==null?void 0:Fe.componentName]),N=n.resolveMultiInputType(E,T),M=C.useMemo(()=>n.getCustomVisualInputCards({frame:i,configCard:E,isMultiInputVisual:N==="multiple"}),[i,E,N]),j=C.useMemo(()=>{const ee=M.findIndex(Se=>(Se==null?void 0:Se.id)===(l==null?void 0:l.id));return ee<0?-1:n.getSlotIndexForCard(l,ee)},[M,l]),O=C.useMemo(()=>!E||N!=="multiple"||j<0?l.type:n.getEffectiveCardTypeForSlot(l,j,T==null?void 0:T.slots)??l.type,[E,N,j,l,T==null?void 0:T.slots]),D=O??l.type,L=C.useMemo(()=>D===l.type?l:{...l,type:D},[l,D]),R=C.useMemo(()=>O!==l.type?{...l,type:O}:l,[l,O]),{data:p,isLoading:F,isFetching:k,errorMessage:P,errorSql:V,pagination:z}=n.useEditorCardQuery(R),{handleOpenInEditor:_,handleDebugWithAssistant:q}=Vn(P,V||l.sql||l.python),W=C.useMemo(()=>(p==null?void 0:p.records)||[],[p==null?void 0:p.records]),{setCard:$,updateCardInFrame:U}=t.useEditorActions(),{data:se}=n.useTopoJson(L),ie=L.id,le=L.config,de=L.interactionConfig,me=L.customCfg,ue=L.preferences,Ne=L.queryConfig,we=!!L.sql,Te=p==null?void 0:p.records,Z=C.useMemo(()=>({id:ie,type:D,config:le,interactionConfig:de,sql:we?"__editor_sql__":""}),[ie,D,le,de,we]),je=C.useMemo(()=>{var ee;return D!=="pivotTable"||!((ee=p==null?void 0:p.records)!=null&&ee.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[D,p==null?void 0:p.records,p==null?void 0:p.columnSubtotalMeta,p==null?void 0:p.subtotalColumns,p==null?void 0:p.pivotSchema,p==null?void 0:p.groupByColumns]),Ie=n.usePivotTableConfig(L,je),ne=()=>{m(!0)},Ae=C.useMemo(()=>{const ee=typeof window<"u"?window.location.href:"",Se=typeof navigator<"u"?navigator.userAgent:"",fe=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:g,tokenContext:y,systemState:{cardConfig:l.config,dataSource:l.dataSource,dashboardFilters:h,errorMessage:P||void 0,errorSql:V||l.sql||l.python,generatedSql:V||l.sql},metadata:{url:ee,userAgent:Se,timestamp:new Date().toISOString(),viewport:fe}}},[g,y,l,h,P,V]),Le=(ee,Se)=>{var De,Oe;const fe={...l,paginationConfig:{page:ee+1,pageSize:Se}};$(fe),U(fe),l.sql&&((Oe=(De=l.preferences)==null?void 0:De.tablePrefs)!=null&&Oe.enableDevModePagination)&&b(!0)},ae=ee=>{var De,Oe,Qe,Ke,Ge;const Se=n.sortStateToSortByColumns(ee,(De=l.config)==null?void 0:De.metricColumns,(Oe=l.config)==null?void 0:Oe.groupByColumns,(Qe=l.config)==null?void 0:Qe.detailColumns),fe={...l,config:{...l.config||{},sortByColumns:Se}};$(fe),U(fe),l.sql&&((Ge=(Ke=l.preferences)==null?void 0:Ke.tablePrefs)!=null&&Ge.enableDevModePagination)&&b(!0)},ve=C.useMemo(()=>!ie||!Te?null:n.createChartConfig({card:Z,data:Te,cardType:D,queryConfig:Ne,customCfg:me,preferences:ue,topoJson:se}),[Z,ie,me,ue,Ne,Te,D,se]);function ye(ee){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:ee})})}function K(){var ee;if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!F&&!k)return P?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ps,{error:P,errorSql:V||l.sql||l.python,onOpenInEditor:_,onDebugWithAssistant:q,onSendFeedback:ne,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(n.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((F||k)&&(!(p!=null&&p.records)||p.records.length===0))return D==="table"||D==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!L.id)return null;if(D==="custom")return ye(l);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(D)&&ve)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:F||k?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:ve})});if(D==="table"||D==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.TableVisual,{card:L,data:W,comparisonMetadata:(ee=p==null?void 0:p.metadata)==null?void 0:ee.comparisonMetadata,paginationMetadata:z,onPaginationChange:Le,onSortChange:ae,isLoading:F||k})});if(D==="pivotTable"&&Ie)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.PivotTableTanstack,{card:L,data:Ie.data,options:Ie.options,onAggregationChange:Se=>{const fe=n.handleAggregationChange(Se,l.config),De={...l,config:fe};$(De),U(De)},onAggregationLabelChange:Se=>{const fe=n.handleAggregationLabelChange(Se,l.config),De={...l,config:fe};$(De),U(De)}})});if(D==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.AggregateTable,{card:L,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:z,onPaginationChange:Le,onAggregationChange:Se=>{const fe=n.handleAggregationChange(Se,l.config),De={...l,config:fe};$(De),U(De)},isLoading:F||k})})}return e.jsxs(n.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none bg-card text-card-foreground",s),style:{...u.cardFrameStyle,...a},...r,children:[(F||k)&&(p==null?void 0:p.records)&&p.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),o&&e.jsxs(n.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:u.cardGutterStyle,children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(n.EditableText,{value:l.title,onSave:ee=>$({...l,title:ee}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:l}),e.jsx(Me.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(pr,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(l.description||"").trim(),onSave:ee=>$({...l,description:ee.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),S&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:S.title||S.column,onSave:ee=>B({...S,title:ee}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:S})]})]}),d&&l.inlineFilters&&l.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:u.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:l,sheetId:v||"",inlineFilterValues:x,setInlineFilterValue:ee=>w(l.id,ee),removeInlineFilterValue:ee=>A(l.id,ee)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col px-4"),style:u.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:K()}),n.isCardSummaryVisibleOnCard(L)&&e.jsx("div",{className:"pt-3",children:e.jsx(n.CardSummary,{card:L,mode:"editor"})})]}),e.jsx(n.FeedbackDialog,{open:f,onOpenChange:m,feedbackData:Ae,showDebugInfo:!0})]})}const as=({language:s,value:a,onChange:r,readonly:l})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:l,embedded:!0}),fr=()=>e.jsxs(n.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.DialogTitle,{children:"Customize Card"})}),e.jsxs(n.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),gr=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:l,onCodeChange:u})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{language:"json",value:r,onChange:l})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(as,{language:"javascript",value:s,onChange:u})})]}),br=({error:s,hasCardCustomConfig:a,onReset:r,onApply:l,onClose:u})=>e.jsxs(n.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:r,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:l,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:u,variant:"outline",children:"Close"})]});function jr({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[l,u]=C.useState(!1),[c,o]=C.useState(""),[d,i]=C.useState(""),[x,h]=C.useState(""),[v,f]=C.useState(""),m=t.useEditorStore(j=>j.card),g=Me.useEffectiveEditorCardType(),y=t.useEditorStore(j=>j.card.customCfg),b=y?JSON.stringify(y,null,2):"",w=C.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:A}=n.useEditorCardQuery(w),{data:B}=n.useTopoJson(m),{setCardCustomCfg:S,setCustomVisualCode:E}=t.useEditorActions(),I=j=>{var O,D;return JSON.stringify({...j,data:{...j.data,datasets:(D=(O=j.data)==null?void 0:O.datasets)==null?void 0:D.map(L=>({...L,data:[]}))}},null,2)},T=()=>{var O,D;if(!((O=A==null?void 0:A.records)!=null&&O.length))return;const j=n.createChartConfig({card:m,data:A.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:B});if(j){o(I(j)),h(((D=m.preferences)==null?void 0:D.customVisualCode)||"");const L=n.merge(j,y);i(I(L))}},N=()=>{try{if(x&&E(x),d){const j=JSON.parse(d),O=n.getObjectDiff(JSON.parse(c),j);S(O),f("")}}catch{f("Invalid JSON configuration")}},M=Object.keys(y||{}).length===0;return e.jsxs(n.Dialog,{open:l,onOpenChange:u,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:T,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",M?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(n.Settings,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{tooltip:"Customize Visual",onClick:T,className:t.cn(M?"":"text-green-600 hover:text-green-700",a),children:e.jsx(n.Settings,{className:"h-4 w-4"})})}),e.jsxs(n.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(fr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(zn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(gr,{customCode:x,cardCustomCfgString:b,mergedConfig:d,onConfigChange:j=>i(j??""),onCodeChange:j=>h(j??"")})]}),e.jsx(br,{error:v,hasCardCustomConfig:!!y,onReset:()=>{i(c),S(null)},onApply:N,onClose:()=>u(!1)})]})]})}function vr(s){let a=0;for(let l=0;l<s.length;l++)a=s.charCodeAt(l)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function yr(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function fs({chartType:s,chartName:a,isCustom:r=!1,className:l="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,l);const u=n.getAutoDetectedChartIcon(a);if(u)return C.cloneElement(u,{className:l});const c=yr(a),o=vr(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",l),style:{backgroundColor:o},children:c})}function Nr({isStarred:s,onClick:a,className:r}){const l=u=>{u.stopPropagation(),u.preventDefault(),a(u)};return e.jsx("button",{type:"button",onClick:l,className:t.cn("flex items-center justify-center rounded-control p-0.5 transition-all","hover:bg-muted/80",r),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(n.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function pn({chartType:s,chartName:a,isCustom:r=!1,pluginName:l,isStarred:u,showStar:c=!0,isSelected:o=!1,onSelect:d,onToggleStar:i}){return e.jsxs("div",{className:"group relative",children:[c&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",u?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(Nr,{isStarred:u,onClick:()=>i()})}),r&&l&&e.jsx("div",{className:"absolute right-1 top-1 z-10",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",children:l})]})}),e.jsxs("button",{type:"button",onClick:d,"aria-pressed":o,className:t.cn("flex w-full flex-col items-center justify-center gap-1.5 rounded-control border border-input bg-background px-2 py-2.5 transition-colors","hover:border-foreground/30 hover:bg-muted/40",o&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(fs,{chartType:s,chartName:a,isCustom:r,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:a})]})]})}const fn=[{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 _n({onChartSelect:s,onClose:a}){const[r,l]=C.useState(""),{starredCharts:u,isStarred:c,toggleStar:o}=n.useStarredChartsStore(),{data:d=[],isLoading:i}=n.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:h,setIsDevMode:v}=t.useEditorStore(j=>j.actions),f=t.useEditorStore(j=>j.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:y,setQueryConfig:b,replaceFrameCards:w,clearModeDrafts:A,initializeModeDrafts:B}=t.useEditorActions(),S=C.useMemo(()=>{if(!r)return fn;const j=r.toLowerCase();return fn.filter(O=>O.name.toLowerCase().includes(j))},[r]),E=C.useMemo(()=>{const j=d.filter(D=>D.componentType==="chart"&&D.pluginType!=="standard");if(!r)return j;const O=r.toLowerCase();return j.filter(D=>D.name.toLowerCase().includes(O))},[d,r]),I=j=>{m(null),h({}),y("builtin"),x(j),["custom","text","map"].includes(j)&&(v(!0),b(void 0)),s==null||s(j),a==null||a()},T=j=>{m(null),h({}),y("builtin"),b(void 0);const O=n.resolveMultiInputTypeFromVisual(j);if(O==="multiple"&&j.slots&&j.slots.length>0){A();const L=n.createCardsFromSlots(j.slots,j,f);w(L),L[0]&&B(L[0]),a==null||a();return}else x("custom"),g({type:"component",visualType:O,url:j.url,componentName:j.name,icon:j.icon,pluginChartType:j.chartType,minInputs:j.minInputs,maxInputs:j.maxInputs});s==null||s("custom",j),a==null||a()},N=j=>{const O={type:"default",id:j.id,name:j.name};o(O)},M=j=>{const O={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};o(O)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:j=>l(j.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),e.jsxs("div",{className:"max-h-[360px] overflow-y-auto pr-1",children:[S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:S.map(j=>e.jsx(pn,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:c("default",j.id),onSelect:()=>I(j.id),onToggleStar:()=>N(j)},j.id))}),E.length>0&&e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs("div",{className:"my-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Custom charts"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:E.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:E.map((j,O)=>e.jsx(pn,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:c("custom",j.name),onSelect:()=>T(j),onToggleStar:()=>M(j)},`${j.url}-${j.name}-${O}`))})]}),i&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),S.length===0&&E.length===0&&!i&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Cr({selectedChart:s,onChartChange:a}){var I,T,N,M;const r=t.useEditorStore(j=>j.card),l=t.useEditorStore(j=>j.frame),u=t.useEditorStore(j=>j.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:i}=t.useEditorActions(),x=C.useMemo(()=>n.findCustomVisualConfigCard(l,r),[l,r]),{manifest:h}=n.useCustomVisual(((I=x==null?void 0:x.customCardPreferences)==null?void 0:I.url)||""),v=C.useMemo(()=>{var j;return(j=h==null?void 0:h.visuals)==null?void 0:j.find(O=>{var D;return O.name===((D=x==null?void 0:x.customCardPreferences)==null?void 0:D.componentName)})},[h,(T=x==null?void 0:x.customCardPreferences)==null?void 0:T.componentName]),f=n.resolveMultiInputType(x,v)==="multiple",m=Me.useEffectiveEditorCardType(),g=f?m:s??r.type,y=(N=r==null?void 0:r.customCardPreferences)==null?void 0:N.componentName,b=(M=x==null?void 0:x.customCardPreferences)==null?void 0:M.componentName,w=f&&!!b,A=C.useMemo(()=>{const j=n.chartTypes.find(O=>O.id===g);return j?j.label:g==="custom"?y||"Custom Visual":"Select chart type"},[g,y]),B=C.useMemo(()=>{const j=n.chartTypes.find(O=>O.id===g);if(j){const O=j.icon;return e.jsx(O,{className:"h-4 w-4"})}if(g==="custom"&&y){const O=n.getAutoDetectedChartIcon(y);return O||e.jsx(fs,{chartName:y,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Fa,{className:"h-4 w-4"})},[g,y]);return{displayChartType:g,displayLabel:A,displayIcon:B,showBadge:w,badgeLabel:b,isMultiInputContext:f,handleChartSelect:j=>{a==null||a(j)},handleClearCustomVisual:j=>{j.stopPropagation();const O={...r,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([O]),o(),d(O),u&&i(!0),a==null||a("bar")}}}function Sr({selectedChart:s,onChartChange:a,variant:r="ghost",className:l}){const[u,c]=C.useState(!1),{displayLabel:o,displayIcon:d,showBadge:i,badgeLabel:x,handleChartSelect:h,handleClearCustomVisual:v}=Cr({selectedChart:s,onChartChange:a}),f=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",l),children:[e.jsxs(t.Popover,{open:u,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:f?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":u,className:"flex h-9 w-full items-center justify-between gap-2 border-b border-border bg-card px-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:o})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",u&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":u,className:t.cn("w-full justify-between gap-2",r==="ghost"&&"border border-border/70 bg-background text-foreground/90",r==="outline"&&"border-border/70 bg-background text-foreground/90",r==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:m=>m.preventDefault(),children:e.jsx(_n,{onChartSelect:m=>h(m),onClose:()=>c(!1)})})]}),i&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(n.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:v,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}const jt={table:t.Table2,bar:n.ChartColumnIncreasing,line:n.ChartLine,stackedBar:n.ChartColumnStacked,stackedLine:n.MdStackedLineChart,scatter:n.ChartScatter,bubble:n.TbChartBubble,pie:n.ChartPie,doughnut:n.Donut,kpi:n.TiSortNumerically,treemap:n.TbChartTreemap,bullet:n.BulletChartIcon,funnel:n.TbChartFunnel,tornado:n.Tornado,heatmap:n.Grid3x3,range:n.ChartNoAxesGantt,radar:n.Radar,polarArea:n.PiChartPolar,text:n.BookType,map:n.Map},It={table:"Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},qn=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],$n=6;function wr({selectedChart:s,onChartChange:a}){var A,B;const[r,l]=C.useState(!1),u=t.useEditorStore(S=>S.card),{setCardType:c,setCardPreferences:o}=t.useEditorStore(S=>S.actions),{setCardCustomCfg:d,setCustomCardPreferences:i,setQueryConfig:x,replaceFrameCards:h,clearModeDrafts:v,initializeModeDrafts:f}=t.useEditorActions(),{starredCharts:m}=n.useStarredChartsStore(),{data:g=[]}=n.useCustomVisualsQuery(),y=C.useMemo(()=>{const S=m.filter(N=>N.type==="default"?!0:g.some(M=>M.name===N.id)),E=new Set(S.map(N=>N.id)),I=qn.filter(N=>!E.has(N.id));return[...S.map(N=>({id:N.id,label:N.name,icon:N.type==="default"?jt[N.id]:void 0,isCustom:N.type==="custom",url:N.url})),...I.map(N=>({id:N.id,label:It[N.id]??N.id,icon:jt[N.id],isCustom:!1}))].slice(0,$n)},[m,g]),b=s==="custom"&&((A=u==null?void 0:u.customCardPreferences)==null?void 0:A.componentName);return y.some(S=>{var E;return S.isCustom?b&&((E=u==null?void 0:u.customCardPreferences)==null?void 0:E.componentName)===S.id:s===S.id})||(s==="custom"?(B=u==null?void 0:u.customCardPreferences)!=null&&B.componentName:It[s]),e.jsxs("div",{className:"px-4 pb-3 pt-4",children:[e.jsx("p",{className:"pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chart type"}),e.jsx(Kn,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function Kn({selectedChart:s,onChartChange:a,compactMore:r=!1}){var I,T;const[l,u]=C.useState(!1),c=t.useEditorStore(N=>N.card),{setCardType:o,setCardPreferences:d}=t.useEditorStore(N=>N.actions),{setCardCustomCfg:i,setCustomCardPreferences:x,setQueryConfig:h,replaceFrameCards:v,clearModeDrafts:f,initializeModeDrafts:m}=t.useEditorActions(),{starredCharts:g}=n.useStarredChartsStore(),{data:y=[]}=n.useCustomVisualsQuery(),b=((I=c==null?void 0:c.customCardPreferences)==null?void 0:I.componentName)??null,w=C.useMemo(()=>{const N=g.filter(L=>L.type==="default"?!0:y.some(R=>R.name===L.id)),M=new Set(N.map(L=>L.id)),j=qn.filter(L=>!M.has(L.id)),O=[...N.map(L=>({id:L.id,label:L.name,icon:L.type==="default"?jt[L.id]:void 0,isCustom:L.type==="custom",url:L.url})),...j.map(L=>({id:L.id,label:It[L.id]??L.id,icon:jt[L.id],isCustom:!1}))];if(!O.some(L=>L.isCustom?s==="custom"&&L.id===b:L.id===s))if(s==="custom"&&b){const L=y.find(R=>R.name===b);L&&O.unshift({id:L.name,label:L.name,icon:void 0,isCustom:!0,url:L.url})}else s&&jt[s]&&O.unshift({id:s,label:It[s]??s,icon:jt[s],isCustom:!1});return O.slice(0,$n)},[g,y,s,b]),A=s==="custom"&&b,B=N=>{if(N.isCustom){const M=y.find(D=>D.name===N.id);if(!M)return;i(null),d({}),h(void 0);const j=n.resolveMultiInputTypeFromVisual(M);if(j==="multiple"&&M.slots&&M.slots.length>0){f();const D=n.createCardsFromSlots(M.slots,M,c);v(D),D[0]&&m(D[0]);return}o("custom"),x({type:"component",visualType:j,url:M.url,componentName:M.name,icon:M.icon,pluginChartType:M.chartType,minInputs:M.minInputs,maxInputs:M.maxInputs}),a("custom");return}a(N.id)},S=w.some(N=>{var M;return N.isCustom?A&&((M=c==null?void 0:c.customCardPreferences)==null?void 0:M.componentName)===N.id:s===N.id}),E=S?"More":s==="custom"?((T=c==null?void 0:c.customCardPreferences)==null?void 0:T.componentName)||"Custom":It[s]||"More";return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex h-7 items-center overflow-hidden rounded-control border border-input bg-background",children:w.map(N=>{var O;const M=N.icon,j=N.isCustom?A&&((O=c==null?void 0:c.customCardPreferences)==null?void 0:O.componentName)===N.id:s===N.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>B(N),"aria-label":N.label,"aria-pressed":!!j,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",j&&"bg-foreground/[0.08] font-medium text-foreground"),children:[M?e.jsx(M,{className:"h-3.5 w-3.5"}):e.jsx(fs,{chartName:N.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:N.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:N.label})]},`${N.isCustom?"custom":"default"}-${N.id}`)})}),e.jsxs(t.Popover,{open:l,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":E,className:t.cn("inline-flex h-7 items-center gap-1 rounded-control transition-colors hover:bg-muted/50",r?"w-7 justify-center":"px-2 text-[12px]",!r&&(S?"text-muted-foreground":"text-foreground")),children:[!r&&e.jsx("span",{className:"truncate",children:E}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",l&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:N=>N.preventDefault(),children:e.jsx(_n,{onChartSelect:N=>{a(N),u(!1)},onClose:()=>u(!1)})})]})]})}function Tr(){const s=t.useEditorStore(i=>{var x,h;return(h=(x=i.card.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:r,setCardPreferences:l}=t.useEditorStore(i=>i.actions),u=i=>{if(r(i),a!=="bullet")return;const x=i==="y"?"horizontal":"vertical",h=t.useEditorStore.getState().card.preferences,v={...h||{},bulletConfig:{...(h==null?void 0:h.bulletConfig)||{},orientation:x}};l(v)};function c(){const i=s??"x",x=()=>{u(i==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:i==="x"?e.jsx(ts,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})})}function o(){const i=()=>{u(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:i,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(ts,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})})}function d(){const i=s??"y",x=()=>{u(i==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:i==="y"?e.jsx(es,{className:"h-3.5 w-3.5"}):e.jsx(ts,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():a==="bullet"?d():c()})}function gs({className:s,triggerVariant:a="icon",label:r="Display Options"}){var y,b,w,A,B,S,E,I,T,N;const l=t.useEditorStore(M=>M.card),{setCardPreferences:u,updateCardInFrame:c,setCard:o}=t.useEditorActions(),[d,i]=C.useState(!1),x=((b=(y=l.preferences)==null?void 0:y.displayOptions)==null?void 0:b.showFilterInfo)??!0,h=((A=(w=l.preferences)==null?void 0:w.displayOptions)==null?void 0:A.showCardToolbar)??!0,v=((S=(B=l.preferences)==null?void 0:B.displayOptions)==null?void 0:S.showChrome)??!0,f=((I=(E=l.preferences)==null?void 0:E.displayOptions)==null?void 0:I.allowScroll)??!0,m=((N=(T=l.preferences)==null?void 0:T.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,g=(M,j)=>{var L;const O={...l.preferences,displayOptions:{...(L=l.preferences)==null?void 0:L.displayOptions,[M]:j}};u(O);const D={...l,preferences:O};o(D),c(D)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:a==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{className:"h-7 w-7 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"Display Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:M=>{g("showFilterInfo",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:M=>{g("showCardToolbar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:v,onCheckedChange:M=>{g("showChrome",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:f,onCheckedChange:M=>{g("allowScroll",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:M=>{g("showInlineFilterBar",M)},onSelect:M=>M.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function bs({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){var E,I,T;const[l,u]=C.useState(!1),c=t.useEditorStore(N=>N.card),o=t.useEditorStore(N=>N.selectedConnectionId),{tokenProps:d}=n.useSemaphorContext(),{setCard:i}=t.useEditorActions(),x=t.useDashboardStore(N=>N.actions.removeCardInlineFilterValue),h=t.useDashboardStore(N=>N.actions.setCardInlineFilterValue),v=t.useEditorStore(N=>N.actions.removeCardInlineFilterValue),f=t.useEditorStore(N=>N.actions.setCardInlineFilterValue),m=t.useDashboardStore(N=>N.isVisualEditing),g=(c==null?void 0:c.inlineFilters)||[],y=((I=(E=d==null?void 0:d.params)==null?void 0:E.calendarContext)==null?void 0:I.tz)||((T=d==null?void 0:d.params)==null?void 0:T.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(N){var z,_,q,W,$,U,se;const M=((q=(_=(z=c==null?void 0:c.dataSource)==null?void 0:z.selectedEntities)==null?void 0:_[0])==null?void 0:q.database)||"",j=N.qualifiedFieldName||N.name;if(g.find(ie=>n.doesStoredFilterMatchField(ie,N)))return;const D=N.qualifiedFieldName?N.qualifiedFieldName.split(".").slice(0,-1).join("."):N.qualifiedEntityName||N.entityName,R=t.fmt(N.name),p=n.buildFilterFieldMeta(N),F=n.buildFilterSemanticContext(c==null?void 0:c.dataSource,{connectionId:o||((W=c==null?void 0:c.dataSource)==null?void 0:W.connectionId),connectionType:($=c==null?void 0:c.dataSource)==null?void 0:$.connectionType}),k=n.isCalculatedFilterField(p),P=!!(((U=c==null?void 0:c.dataSource)==null?void 0:U.mode)==="semanticDomain"&&((se=F==null?void 0:F.selectedEntities)!=null&&se.length||F!=null&&F.semanticDomainId)),V={id:t.v4(),column:j,title:N.label||N.name,dataType:N.dataType,table:N.entityName||"",database:M,qualifiedTableName:D,connectionId:o||"",operation:"in",sql:k||P?"":n.getDefaultFilterSql(N.dataType,D,R),fieldMeta:p,semanticContext:F,width:250};i({...c,inlineFilters:[...g,V]})}function w(N){const M=g.filter(j=>j.id!==N);i({...c,inlineFilters:M}),m?v(c.id,N):x(c.id,N)}function A(N,M){const j=g.map(R=>R.id===N?{...R,...M}:R);if(i({...c,inlineFilters:j}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const D=j.find(R=>R.id===N);if(!D)return;const L=t.buildFilterValueFromDefaults(D,y);L?m?f(c.id,L):h(c.id,L):m?v(c.id,N):x(c.id,N)}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 S=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",S&&"w-full",s),children:e.jsxs(t.Popover,{open:l,onOpenChange:u,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:S?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(on,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(on,{className:"h-3.5 w-3.5"}),g.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",S&&"z-[60]"),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(n.DndContext,{collisionDetection:n.closestCenter,children:e.jsx(n.SortableContext,{items:[],strategy:n.verticalListSortingStrategy,children:e.jsx(n.FieldsList,{context:"inline-filter",onFieldSelect:b,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(N=>e.jsx(Er,{filter:N,onUpdate:M=>A(N.id,M),onRemove:()=>w(N.id)},N.id))})]})]})})]})})}function Er({filter:s,onUpdate:a,onRemove:r}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(n.CustomFilterPopover,{filter:s,variant:"inline",onAccept:l=>a(l),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(n.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:r,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const Ir={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function kr(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const Dr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function qt(s,a){return`${s}:${a}`}function Ar(s,a,r){const l=new Set(r.filter(c=>c.target!=="sql_param").map(c=>qt(c.controlId,c.target))),u=a.map(c=>{const o=n.getCompatibleBindingTargetOptions({card:s,control:c}).map(h=>h.value),d=Dr[c.type],x=[...d?[d]:[],...o.filter(h=>h!==d)].find(h=>!l.has(qt(c.id,h)));return x?{controlId:c.id,target:x}:null}).find(Boolean);return u?{controlId:u.controlId,target:u.target,mapping:{}}:null}function Mr({card:s,dashboardControls:a,bindings:r,onChange:l,availableFieldChoices:u,availableMetricChoices:c,suppressTransientStaleState:o=!1}){const d=[...a,...s.controls||[]],[i,x]=C.useState({}),h=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),v=n.getBindingTargetSuggestions(s),f=new Set(r.map(B=>qt(B.controlId,B.target))),m=d.some(B=>n.getCompatibleBindingTargetOptions({card:s,control:B}).some(S=>!f.has(qt(B.id,S.value)))),g=o?0:r.reduce((B,S)=>{const E=y(S.target),I=Object.values(S.mapping).filter(T=>{const N=S.target==="config_metric_selector"||S.target==="config_field_selector"?typeof T=="string"?T:T==null?void 0:T.id:typeof T=="string"?T:void 0;return typeof N=="string"&&!E.some(M=>M.value===N)}).length;return B+I},0);function y(B){var S,E,I,T;switch(B){case"config_metric_selector":return c?c.filter(N=>!!N.target).map(N=>({value:N.target.id,label:N.target.label||N.option.label,target:N.target})):((E=(S=s.config)==null?void 0:S.metricColumns)==null?void 0:E.map(N=>({value:N.id,label:N.label||N.id,target:N})))||[];case"config_field_selector":return u?u.filter(N=>!!N.target).map(N=>({value:N.target.id,label:N.target.label||N.option.label,target:N.target})):((T=(I=s.config)==null?void 0:I.groupByColumns)==null?void 0:T.map(N=>({value:N.id,label:N.label||N.id,target:N})))||[];case"config_aggregation":return(v.config_aggregation||[]).map(N=>({value:N,label:N}));case"config_grain":return(v.config_grain||[]).map(N=>({value:N,label:N.charAt(0).toUpperCase()+N.slice(1)}));default:return[]}}const b=(B,S)=>{l(r.map((E,I)=>I!==B?E:S(E)))},w=B=>{l(r.filter((S,E)=>E!==B))},A=()=>{const B=Ar(s,d,r);B&&l([...r,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=h.map(({controlId:S,paramId:E})=>{const I=d.find(T=>T.id===S);return I?{id:S,paramId:E,label:I.label,reference:`[[param.${E}]]`}:{id:S,paramId:E,label:S,reference:`[[param.${E}]]`}});return e.jsx("div",{className:"space-y-2",children:B.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):B.map(S=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:S.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:S.reference}),e.jsx(n.CopyButton,{text:S.reference,ariaLabel:`Copy ${S.reference}`})]})]})},`${S.id}:${S.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(n.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,r.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is not using any controls yet."}):r.map((B,S)=>{const E=v[B.target]||[],I=d.find(p=>p.id===B.controlId),T=I?n.ensureManualSource(I):null,N=(T==null?void 0:T.source.kind)==="manual"?T.source.options:[],M=y(B.target),j=Array.from(new Set([...N.map(p=>p.value),...Object.keys(B.mapping)])).map(p=>{const F=N.find(k=>k.value===p);return{value:p,label:(F==null?void 0:F.label)||p}}),O=`${B.controlId}-${B.target}-${S}`,D=i[O]??S===0,L=Object.keys(B.mapping).length,R=I!=null&&I.type?Ir[I.type]||I.type:null;return e.jsxs(n.Collapsible,{open:D,onOpenChange:p=>x(F=>({...F,[O]:p})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[D?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(n.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(I==null?void 0:I.label)||"Control"}),R?e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:R}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:L>0?`${L} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>w(S),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]}),e.jsx(n.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:j.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"Add choices to this control first so you can decide what each choice changes in the card."}):M.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No matching targets are available for this binding yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs",children:"Map each choice"}),e.jsx("div",{className:"space-y-2",children:j.map(p=>{const F=B.mapping[p.value],k=B.target==="config_metric_selector"||B.target==="config_field_selector"?typeof F=="string"?F:F==null?void 0:F.id:typeof F=="string"?F:void 0,P=!o&&typeof k=="string"&&!M.some(_=>_.value===k),V=kr(F,k),z=k&&P?[...M,{value:k,label:"Needs remap",target:F}]:M;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:p.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:k||"__none__",onValueChange:_=>b(S,q=>{if(q.target==="config_metric_selector"){const $={...q.mapping};if(_==="__none__")delete $[p.value];else{const U=z.find(se=>se.value===_);U!=null&&U.target?$[p.value]=U.target:delete $[p.value]}return{...q,mapping:$}}if(q.target==="config_field_selector"){const $={...q.mapping};if(_==="__none__")delete $[p.value];else{const U=z.find(se=>se.value===_);U!=null&&U.target?$[p.value]=U.target:delete $[p.value]}return{...q,mapping:$}}const W={...q.mapping};return _==="__none__"?delete W[p.value]:W[p.value]=_,{...q,mapping:W}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),z.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),P?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(n.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",V?` · Previously: ${V}`:""]})]}):null]})]},`${B.controlId}-${B.target}-${p.value}`)})}),E.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",E.join(", ")]})]})})]},O)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(n.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Lr=[];function Gn({className:s,triggerVariant:a="icon",label:r="Controls"}){var D,L;const{handleOpenChange:l,preventPassiveDismissDuringCreate:u,resolvedOpen:c,setIsCreateFlowActive:o}=Me.useCreateFlowOverlayState({}),d=t.useEditorStore(R=>R.card),i=t.useEditorStore(R=>R.frame),x=t.useDashboardStore(R=>R.dashboard),v=t.useDashboardStore(R=>R.dashboard.controls)||Lr,{setCard:f,updateCardInFrame:m}=t.useEditorActions(),[g,y]=C.useState(null);C.useEffect(()=>{c&&!g&&(d!=null&&d.id)&&y(d.id)},[d==null?void 0:d.id,c,g]),C.useEffect(()=>{!c&&g!==null&&y(null)},[c,g]);const b=C.useMemo(()=>g?(i==null?void 0:i.cards.find(R=>R.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,i==null?void 0:i.cards,g]),w=(b==null?void 0:b.controls)||[],A=b?n.collectDashboardControlIds(x,{excludeCardId:b.id}):v.map(R=>R.id),B=((b==null?void 0:b.controlBindings)||[]).filter(R=>R.target!=="sql_param"),S=n.buildCardControlUsageById({card:b,controls:w}),E={choices:n.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((D=b==null?void 0:b.config)==null?void 0:D.groupByColumns)||[]).map(R=>[R.id,R]))},I={choices:n.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((L=b==null?void 0:b.config)==null?void 0:L.metricColumns)||[]).map(R=>[R.id,R]))},T=E.choices.map(R=>({option:R,target:E.targetMap[R.value]})),N=I.choices.map(R=>({option:R,target:I.targetMap[R.value]})),M=(R,p)=>{if(!b)return;const F=(p==null?void 0:p.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:p.oldId,newId:p.newId}):(p==null?void 0:p.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:p.controlId}):b,k={...F,controls:R,controlBindings:n.syncStructuralBindingsWithControls(F.controlBindings,R)};m(k),(d==null?void 0:d.id)===k.id&&f(k)},j=R=>{if(!b)return;const p={...b,controlBindings:n.mergeConfigBindingsWithSqlParamBindings(R,b.controlBindings)};m(p),(d==null?void 0:d.id)===p.id&&f(p)},O=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",O&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:O?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(w.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),w.length+B.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:w.length+B.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":w.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),w.length+B.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:w.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),b!=null&&b.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Me.ControlDefinitionListEditor,{scope:"card",card:b,controls:w,reservedControlIds:A,usageByControlId:S,availableFieldChoices:T,availableMetricChoices:N,onCreateFlowActiveChange:o,onChange:(R,p,F)=>M(R,F),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),b?e.jsx(Mr,{card:b,dashboardControls:v,bindings:B,onChange:j,availableFieldChoices:T,availableMetricChoices:N}):null]})})]})]})})}function Un({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:l=!0,showDisplayOptions:u=!0}={}){const c=t.useEditorStore(m=>m.card),o=t.useEditorStore(m=>{var g,y;return(y=(g=m.card)==null?void 0:g.preferences)==null?void 0:y.chartOptions}),d=n.getChartGridStyle(o),{setChartGrid:i}=t.useEditorActions();function x(){const m=["xy","none","x","y"],y=(m.indexOf(d)+1)%m.length;i(m[y])}const h=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(c.type),v=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(c.type);return h||v||r||l||u?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[h&&e.jsx(e.Fragment,{children:e.jsx(Tr,{})}),v&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:x,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(hs,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx($t,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(bs,{}),l&&e.jsx(Gn,{}),u&&e.jsx(gs,{})]}):null}function Fr({visible:s}){const a=t.useDashboardStore(o=>o.selectedFrameId),r=n.useManagementStore(o=>o.selectedVisual),l=t.useEditorStore(o=>o.frame),c=!!!(l!=null&&l.visualId||r!=null&&r.id)&&!!a;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 Rr({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var F,k,P,V,z;const l=t.useEditorStore(_=>_.frame),u=t.useEditorStore(_=>_.card),c=t.useEditorStore(_=>_.editorContext),o=(c==null?void 0:c.type)==="documentSection",{setFrame:d,setActiveTabCardId:i,setCard:x,updateCardInFrame:h,clearModeDrafts:v,initializeModeDrafts:f}=t.useEditorActions(),{manifest:m}=n.useCustomVisual(((F=r==null?void 0:r.customCardPreferences)==null?void 0:F.url)||""),g=(k=m==null?void 0:m.visuals)==null?void 0:k.find(_=>{var q;return _.name===((q=r==null?void 0:r.customCardPreferences)==null?void 0:q.componentName)}),b=n.resolveMultiInputType(r,g)==="multiple",w=(g==null?void 0:g.minInputs)??((P=r==null?void 0:r.customCardPreferences)==null?void 0:P.minInputs)??1,A=(g==null?void 0:g.maxInputs)??((V=r==null?void 0:r.customCardPreferences)==null?void 0:V.maxInputs),B=C.useMemo(()=>n.getCustomVisualInputCards({frame:l,configCard:r,isMultiInputVisual:b}),[l,r,b]),S=b?B.filter(Boolean).length:l.cards.length,E=o?!1:A?S<A:!0,I=S>Math.max(w||1,1),T=!!((z=r==null?void 0:r.customCardPreferences)!=null&&z.dataInputCardIds),N=(_,q)=>{_.dataTransfer.setData("tabIndex",q.toString())},M=_=>{_.preventDefault()},j=(_,q)=>{const W=_.dataTransfer.getData("tabIndex");if(W===q.toString())return;const $=Array.from(l.cards),[U]=$.splice(parseInt(W),1);$.splice(q,0,U),d({...l,cards:$})};function O(_){const q=(r==null?void 0:r.id)===_;if(!(T&&q?l.cards.length>1:I))return;let $=l.cards.filter(le=>le.id!==_);b&&!T&&($=n.reindexSlotCards($));const U=$[0],se={...l,cards:$,activeCardId:U.id},ie=_===u.id;ie&&v(),d(se),i(U.id),x(U),ie&&f(U)}function D(_,q){if(!E)return;const W={...l,cards:[...l.cards,q],activeCardId:_.id};d(W),i(q.id)}function L(){if(o)return;if(b&&(r==null?void 0:r.id)===u.id){R(u);return}const _={...u,id:t.v4(),title:`${u.title} Copy`,tabTitle:`${u.tabTitle||u.title} Copy`,customCardPreferences:u.customCardPreferences?{...u.customCardPreferences,slotIndex:b?Math.max(-1,...B.map((q,W)=>n.getSlotIndexForCard(q,W)))+1:u.customCardPreferences.slotIndex}:void 0};D(u,_)}function R(_){var ie;if(o||!E)return;let q=b?"table":"bar",W="Title",$="";const U=b?Math.max(-1,...B.map((le,de)=>n.getSlotIndexForCard(le,de)))+1:S;if(b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)){const le=n.getSlotDefinitionForIndex(g.slots,U);le&&(q=n.getSlotExpectedChartType(le),W=le.label||`Tab ${U+1}`,$=le.description||"")}const se={dataSource:_.dataSource,connectionId:_.connectionId,lastSelectedDatabase:_.lastSelectedDatabase,lastSelectedSchema:_.lastSelectedSchema,lastSelectedTable:_.lastSelectedTable,lastSelectedDatamodelId:_.lastSelectedDatamodelId,id:t.v4(),title:W,tabTitle:W,description:$,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:q,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:U}}};D(_,se)}function p(_,q){return _.cards.length===1&&(q.displayTab===!0||q.displayTab===void 0)||_.activeCardId!==q.id&&(q.displayTab===!0||q.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const W=q.displayTab===void 0?!1:!q.displayTab;x({...q,displayTab:W}),h({...q,displayTab:W})},children:q.displayTab===!0||q.displayTab===void 0?e.jsx(n.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(n.EyeOff,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{variant:"underline",className:"group flex h-9 items-center justify-start gap-1 overflow-x-auto rounded-none border-b-0 border-t border-border bg-background px-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[l.cards.map((_,q)=>{var ie,le;const W=b?n.getSlotIndexForCard(_,q):-1,$=b&&((ie=g==null?void 0:g.slots)!=null&&ie.length)&&W>=0?n.getSlotDefinitionForIndex(g.slots,W):null,U=$?(Array.isArray($.expectedType)?$.expectedType[0]:$.expectedType)||"table":_.type,se=b&&((le=g==null?void 0:g.slots)==null?void 0:le.length)&&g.slots.every(de=>typeof de.position=="number"||typeof de.position=="string"&&!de.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!b&&!o,onDragStart:b||o?void 0:de=>N(de,q),onDragOver:b||o?void 0:M,onDrop:b||o?void 0:de=>j(de,q),className:t.cn("inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[5px] border px-2 text-[12px] font-normal text-muted-foreground transition-colors","mb-0 border-transparent pb-0","hover:bg-muted/40 hover:text-foreground","data-[state=active]:border-border data-[state=active]:bg-card data-[state=active]:text-foreground"),value:_.id,children:[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:n.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:$.label||`Tab ${W+1}`})]})}),e.jsx(t.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:$.label}),$.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:$.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[$.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray($.expectedType)?$.expectedType.join(" / "):$.expectedType}),$.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[p(l,_),e.jsx(n.Editable,{enabled:l.activeCardId===_.id,text:_.tabTitle||_.title,onSave:de=>{x({...u,tabTitle:de}),h({...u,tabTitle:de})},children:_.tabTitle||_.title},_.id)]}),!o&&l.activeCardId===_.id&&!se&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:de=>{de.stopPropagation(),L()}}),!o&&l.activeCardId===_.id&&(T&&(r==null?void 0:r.id)===_.id?l.cards.length>1:I)&&e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>O(_.id)})]},_.id)}),!o&&e.jsx(n.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>R(u),disabled:!E,children:e.jsx(n.Plus,{className:"h-3 w-3"})}),b&&e.jsxs(n.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-1 h-6 gap-1 rounded-[5px] px-2 text-[11px] data-[state=on]:bg-muted data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(n.EyeOff,{className:"h-3 w-3"}):e.jsx(n.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function it({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var ve,ye,K;const r=t.useEditorStore(Q=>Q.frame),l=t.useEditorStore(Q=>Q.card),[u,c]=C.useState(!1),o=C.useMemo(()=>n.findCustomVisualConfigCard(r,l),[r,l]),d=t.useEditorStore(Q=>Q.isSqlRunning);t.useEditorStore(Q=>Q.isDevMode);const{setFrame:i,setActiveTabCardId:x,setCard:h,setRunSql:v,mergeDraftsIntoCard:f,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[y,b]=C.useState({}),[w,A]=C.useState(()=>new Set),{authToken:B}=n.useSemaphorContext(),S=t.getTokenParams(B==null?void 0:B.accessToken),{compiledAppearance:E}=t.useAppearance(),I=C.useMemo(()=>n.buildCustomCardTheme(E),[E]),{getCard:T,manifest:N,isLoading:M}=n.useCustomVisual(((ve=o==null?void 0:o.customCardPreferences)==null?void 0:ve.url)||""),j=(ye=o==null?void 0:o.customCardPreferences)==null?void 0:ye.componentName,O=j?T(j):null,D=(K=N==null?void 0:N.visuals)==null?void 0:K.find(Q=>Q.name===j),L=n.resolveMultiInputType(o,D),R=u&&L==="multiple"&&!!o,p=C.useMemo(()=>n.getCustomVisualInputCards({frame:r,configCard:o,isMultiInputVisual:!0}).map(te=>(te==null?void 0:te.id)===l.id?l:te),[r,o,l]),F=C.useMemo(()=>n.buildSlotOrderedCards(p),[p]),k=C.useMemo(()=>{const Q=p.findIndex(te=>(te==null?void 0:te.id)===l.id);return Q<0?-1:n.getSlotIndexForCard(l,Q)},[p,l]),P=C.useMemo(()=>!o||L!=="multiple"||k<0?l.type:n.getEffectiveCardTypeForSlot(l,k,D==null?void 0:D.slots)??l.type,[o,L,k,l,D==null?void 0:D.slots]),V=C.useMemo(()=>R?{...l,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:P!==l.type?{...l,type:P}:l,[l,P,R]),{data:z,isLoading:_,isFetching:q,isError:W}=n.useEditorCardQuery(V),$=C.useCallback((Q,te)=>{const xe=n.normalizeMultiInputPayload(te);b(pe=>({...pe,[Q]:xe}))},[]),U=C.useCallback((Q,te)=>{A(xe=>{const pe=new Set(xe);return te?pe.add(Q):pe.delete(Q),pe})},[]),se=w.size>0,ie=t.useInteractionStore(Q=>Q.interactionStates),le=t.useDashboardStore(Q=>{var te;return(te=Q.dashboard)==null?void 0:te.id}),de=t.useDashboardStore(Q=>Q.dashboard.filters),me=t.useDashboardStore(Q=>Q.filterValues),ue=t.useDashboardStore(Q=>Q.selectedSheetId),Ne=t.useEditorStore(Q=>Q.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),we=t.useEditorStore(Q=>Q.actions.setCardInlineFilterValue),Te=t.useEditorStore(Q=>Q.actions.removeCardInlineFilterValue),Z=C.useMemo(()=>o?n.buildInlineFilterNodes({card:o,sheetId:ue||"",inlineFilterValues:Ne,setInlineFilterValue:Q=>we(o.id,Q),removeInlineFilterValue:Q=>Te(o.id,Q)}):[],[o,ue,Ne,we,Te]),{cardFilters:je,cardFilterValues:Ie}=C.useMemo(()=>o?n.calculateContextAwareFilters({card:o,interactionStates:ie,currentDashboardId:le,filters:de,filterValues:me,selectedSheetId:ue}):{cardFilters:[],cardFilterValues:[]},[o,ie,le,de,me,ue]);function ne(Q){const te=r.cards.find(xe=>xe.id===Q);te&&(ct.flushPendingEditorDrafts(),f(),Ae(Q),x(Q),m(),g(te))}function Ae(Q){const te=t.useEditorStore.getState().card,xe=t.useEditorStore.getState().frame,pe={...xe,cards:xe.cards.map(ee=>ee.id===te.id?te:ee),activeCardId:Q};i(pe);const Fe=pe.cards.find(ee=>ee.id===Q);Fe.sql&&v(!0),h(Fe)}function Le(){if(M)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!O)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 te=F.map((xe,pe)=>n.getEffectiveCardTypeForSlot(xe,pe,D==null?void 0:D.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[p.map((xe,pe)=>{if(!xe)return null;const Fe=n.getSlotIndexForCard(xe,pe),ee=n.getEffectiveCardTypeForSlot(xe,Fe,D==null?void 0:D.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:U,onDataChange:$,card:xe,effectiveCardType:ee},`${xe.id}-${Fe}`)}),se&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",se&&"opacity-50"),children:e.jsx(C.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(O,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:o,slotOrderedCards:F,slotTypes:te,multiInputData:y,params:S,theme:I,filters:je,filterValues:[...Ie||[],...Ne||[]],inlineFilters:Z})})})})]})}function ae(){var Q;return R?Le():s&&(a||!_&&!q&&!W)?s({card:l,data:z,isLoading:_,isFetching:q,isError:W}):l.type==="kpi"?_||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(Fr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:l,data:z==null?void 0:z.records,isPending:_||q,isError:W,comparisonMetadata:(Q=z==null?void 0:z.metadata)==null?void 0:Q.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(l)&&e.jsx(n.CardSummary,{card:l,mode:"editor"})]})}):l.type==="text"?_||q?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(n.TextCard,{isLoading:d,card:l,data:z==null?void 0:z.records})})})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(zn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ne,value:r.activeCardId,className:"flex grow flex-col gap-2",children:[R?e.jsx("div",{className:"mt-0 grow",children:ae()}):r.cards.map(Q=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:Q.id,children:ae()},Q.id)),e.jsx(Rr,{isPreviewMode:R,onPreviewToggle:c,configCard:o})]})}function Or({onClick:s,className:a}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",a),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Hn({fallbackPreview:s,records:a,title:r,isInspectorOpen:l,onInspectorOpenChange:u}){var L;const c=t.useEditorStore(R=>R.card),o=t.useEditorStore(R=>R.actions.setCard),d=t.useEditorStore(R=>R.actions.updateCardInFrame),i=t.normalizeDynamicRendererSource((L=c.dynamicCardPreferences)==null?void 0:L.rendererCode),[x,h]=C.useState(i),[v,f]=C.useState(i);C.useEffect(()=>{h(i),f(i)},[i,c.id]);const m=C.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),g=C.useMemo(()=>t.validateDynamicRendererSource(m),[m]),y=!!i,b=C.useMemo(()=>{var R;return t.buildCardWithVisualizationMode(c,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((R=c.dynamicCardPreferences)==null?void 0:R.artifactId)||c.id,title:r||c.title})},[c,v,r]),w=!!v,A=m!==v,B=v!==i,S=!m||!g.valid||A||B,E=m?g.valid?A?"Unapplied changes":"Pending save":"Needs attention":"Draft",I=!m||A||B?"outline":"destructive",T=m?g.valid?A?"The preview still reflects the last applied code until you apply this draft.":B?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function N(){if(!g.valid){n.ue.error(g.error||"Visual code is invalid.");return}f(m),n.ue.success("Dynamic preview updated.")}function M(){h(v)}function j(){var p;const R=t.buildCardWithVisualizationMode(c,v?"dynamic":"builtin",{rendererCode:v||void 0,artifactId:((p=c.dynamicCardPreferences)==null?void 0:p.artifactId)||t.v4(),title:r||c.title});o(R),d(R),u(!1),n.ue.success(v?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function O(){h(i),f(i),u(!1)}function D(){h(""),f("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:y?e.jsx(n.PersistedDynamicVisual,{card:c,records:a,title:r,layoutMode:"fill",fallback:s},i||"applied-empty"):e.jsxs("div",{className:"flex h-full min-h-[280px] flex-col items-center justify-center gap-3 rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center",children:[e.jsx("div",{className:"flex size-10 items-center justify-center rounded-full border bg-background",children:e.jsx(n.CodeXml,{className:"text-muted-foreground"})}),e.jsxs("div",{className:"flex max-w-md flex-col gap-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"No applied dynamic visual yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open Customize, paste visual code, and apply it to preview the renderer here."})]}),e.jsx(Or,{onClick:()=>u(!0)})]})}),e.jsx(n.Dialog,{open:l,onOpenChange:R=>{if(!R){O();return}u(!0)},children:e.jsxs(n.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(n.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(n.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(n.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),S&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:I,children:E})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{defaultSize:54,minSize:38,children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx("div",{className:"min-h-0 flex-1 bg-background p-4",children:w?e.jsx(n.PersistedDynamicVisual,{card:b,records:a,title:r,layoutMode:"fill",fallback:s},v||"preview-empty"):e.jsx("div",{className:"flex h-full min-h-[280px] items-center justify-center rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center text-sm text-muted-foreground",children:"Apply valid visual code to preview the dynamic visual here."})})})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:46,minSize:30,children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(n.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n.AlertDialog,{children:[e.jsx(n.AlertDialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{type:"button",size:"sm",variant:"ghost",className:"h-8 gap-1.5 px-2.5 text-xs",disabled:!y&&!m,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(n.AlertDialogContent,{children:[e.jsxs(n.AlertDialogHeader,{children:[e.jsx(n.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(n.AlertDialogDescription,{children:"This removes the saved dynamic renderer and switches the card back to built-in mode. The underlying query and built-in chart type will remain."})]}),e.jsxs(n.AlertDialogFooter,{children:[e.jsx(n.AlertDialogCancel,{children:"Cancel"}),e.jsx(n.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:D,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:M,disabled:!A,children:[e.jsx(ms.RotateCcw,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:N,disabled:!A||!g.valid,children:[e.jsx(n.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[T&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:T}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:x,onValueChange:R=>h(R||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(n.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:T||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:O,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:j,disabled:!B,children:"Accept changes"})]})]})]})})]})}function Qn({onCustomize:s}){const a=t.useEditorStore(x=>x.card),r=t.useEditorStore(x=>x.frame),l=t.useEditorStore(x=>x.actions.setIsShowingVisual),{setVisualizationMode:u,setDynamicCardPreferences:c}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const i=x=>{var h;x==="dynamic"&&!a.dynamicCardPreferences&&c(t.createEmptyDynamicCardPreferences(a.type,(h=a.preferences)==null?void 0:h.displayOptions)),u(x),l(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),i(d?"builtin":"dynamic")},className:"flex items-center justify-between gap-2 text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CodeXml,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{size:"xs",checked:d,onCheckedChange:x=>i(x?"dynamic":"builtin"),onClick:x=>x.stopPropagation()})]}),d&&s?e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),s()},className:"gap-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),"Customize Visual"]}):null]})}const Pr={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},Vt=50,Br=[{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 gn(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),null}}function bt(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 Vr(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=Vt?{value:s}:{value:{...s,records:a.slice(0,Vt),previewMeta:{truncatedRecords:!0,displayedRecords:Vt,totalRecords:a.length}},truncationMessage:`Preview showing first ${Vt} records of ${a.length}. Copy actions include full payload.`}}function Wn({sql:s,showCardDetails:a=!1,debugPayloads:r,className:l}){const[u,c]=C.useState(!1),[o,d]=C.useState(null),i=t.useEditorStore(j=>j.card),x=t.useEditorStore(j=>j.frame),h=t.useEditorStore(j=>j.isDevMode),v=t.useDashboardStore(j=>j.selectedSheetId),f=t.useDashboardStore(j=>{var O;return(O=j.dashboard)==null?void 0:O.id}),{switchEditorMode:m,setRunSql:g}=t.useEditorActions(),y=C.useMemo(()=>({cardId:i.id||null,frameId:x.id||null,sheetId:v||null,dashboardId:f||null}),[i.id,x.id,v,f]),b=C.useMemo(()=>({queryRequest:r==null?void 0:r.queryRequest,queryResponse:r==null?void 0:r.queryResponse,cardConfig:i.config,dataSource:i.dataSource,columns:r==null?void 0:r.columns,dashboardFilters:r==null?void 0:r.dashboardFilters,cardMetadata:y}),[r==null?void 0:r.queryRequest,r==null?void 0:r.queryResponse,r==null?void 0:r.columns,r==null?void 0:r.dashboardFilters,i.config,i.dataSource,y]),w=a&&u&&!!r,A=C.useMemo(()=>[{label:"Card ID",value:i.id||""},{label:"Frame ID",value:x.id||""},{label:"Sheet ID",value:v||""},{label:"Dashboard ID",value:f||""}],[i.id,x.id,v,f]),B=()=>{m("dev",{sqlToLoad:s}),setTimeout(()=>{g(!0)},100)},S=j=>b[j]!==void 0,E=C.useMemo(()=>{if(!o)return null;const j=b[o];if(j===void 0)return null;const O=o==="queryResponse"?Vr(j):{value:j},D=gn(O.value);return D?{target:o,title:bt(o),json:D,truncationMessage:O.truncationMessage}:null},[o,b]),I=E?E.title:"Preview Payload",T=async j=>{const O=b[j];if(O===void 0)return n.ue.error(`No ${bt(j).toLowerCase()} available`),!1;const D=gn(O);if(!D)return n.ue.error(`Unable to serialize ${bt(j).toLowerCase()}`),!1;try{return await Pr.writeTextToClipboard(D)?(n.ue.success(`${bt(j)} copied`),!0):(n.ue.error("Clipboard is not available"),!1)}catch(L){return console.error("Failed to copy debug payload",L),n.ue.error(`Unable to copy ${bt(j).toLowerCase()}`),!1}},N=async()=>E?T(E.target):!1,M=j=>{if(b[j]===void 0){n.ue.error(`No ${bt(j).toLowerCase()} available`);return}d(j)};return e.jsxs("div",{className:t.cn("flex min-h-0 flex-1 flex-col pt-3",l),children:[!h&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:B,variant:"outline",size:"xs",children:[e.jsx(Fn,{className:"mr-1.5 h-3 w-3"}),"View in SQL Editor"]}),a&&e.jsxs(t.Button,{onClick:()=>c(!u),variant:"outline",size:"xs",children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),"Card Details"]})]}),u&&a&&e.jsx("div",{className:"mb-3 rounded-[6px] border border-border bg-card p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-[12px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Card Information"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 rounded-[3px] p-0",onClick:()=>c(!1),children:e.jsx(Me.CircleX,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:A.map(j=>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:j.label}),e.jsx(n.CopyButton,{text:j.value,className:"h-6 w-6 shrink-0"})]}),e.jsx("code",{title:j.value||"N/A",className:"mt-1 block whitespace-normal break-all font-mono text-xs",children:j.value||"N/A"})]},j.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(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8","aria-label":"Preview Payload Menu",children:[e.jsx(n.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),I,e.jsx(t.ChevronDown,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(n.DropdownMenuContent,{align:"start",className:"w-56",children:Br.map(j=>e.jsx(n.DropdownMenuItem,{disabled:!S(j.target),onSelect:()=>M(j.target),className:t.cn(o===j.target&&"bg-accent"),children:j.label},`preview-${j.target}`))})]})}),E&&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:[E.title," Preview"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(n.CopyButton,{text:E.json,className:"h-6 w-6",ariaLabel:"Copy Payload",onCopy:N}),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"]})]})]}),E.truncationMessage&&e.jsx("p",{className:"text-xs text-muted-foreground",children:E.truncationMessage}),e.jsx("div",{className:"max-h-80 overflow-auto",children:e.jsx(n.CodeHighlighter,{code:E.json,language:"json"})})]})]})]})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex h-7 shrink-0 items-center justify-between border-b border-border px-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),e.jsx("span",{className:"text-[12px] text-muted-foreground",children:"Generated query"})]}),e.jsx(n.CopyButton,{text:s,className:"h-5 w-5 rounded-[3px] px-0 text-muted-foreground hover:bg-muted hover:text-foreground"})]}),e.jsx("div",{className:"min-h-[80px] flex-1 px-3 py-2",children:e.jsx(t.CodeEditor,{value:s,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Executed SQL"})})]})]})}function rs({children:s,visualAsideControl:a,mode:r="both",isDynamicInspectorOpen:l,onDynamicInspectorOpenChange:u}){var Le;const c=n.useQueryClient(),o=t.useEditorStore(ae=>ae.frame),d=t.useEditorStore(ae=>ae.card),i=d.type==="table"||d.type==="detailTable",x=t.useEditorStore(ae=>ae.isDevMode),h=t.useEditorStore(ae=>ae.editorContext),v=(h==null?void 0:h.type)==="documentSection",f=t.useEditorStore(ae=>ae.isShowingVisual),m=t.useEditorStore(ae=>ae.actions.setIsShowingVisual),g=t.useDashboardStore(ae=>ae.isVisualEditing),{isConsoleMode:y}=n.useDashboardPreferences(),b=t.useEditorStore(ae=>ae.pythonStdOut),w=t.useEditorStore(ae=>ae.actions.setRunSql),A=Me.useEffectiveEditorCardType(),S=t.getVisualizationMode(d)==="dynamic",[E,I]=C.useState(!1),T=l??E,N=u??I,{setFrame:M,setCard:j,setActiveTabCardId:O,setCardPreferences:D,mergeDraftsIntoCard:L,clearModeDrafts:R,initializeModeDrafts:p,updatePageSize:F,setCardType:k}=t.useEditorActions(),P=C.useMemo(()=>A!==d.type?{...d,type:A}:d,[d,A]),{data:V,isLoading:z,isFetching:_,errorMessage:q,errorSql:W,refetch:$,queryKey:U,pagination:se}=n.useEditorCardQuery(P),ie=C.useRef(U);ie.current=U;const{handleDebugWithAssistant:le}=Vn(q,W),de=C.useMemo(()=>(V==null?void 0:V.records)||[],[V==null?void 0:V.records]),{cardFilterValues:me}=n.useCardFilterValues((d==null?void 0:d.id)??""),[ue,Ne]=C.useState(!1);C.useEffect(()=>{_||Ne(!1)},[_]),C.useEffect(()=>{i&&!f&&!x&&!y&&m(!0)},[y,x,i,f,m]);function we(ae,ve){var Q,te;const ye={...d,paginationConfig:{page:ae+1,pageSize:ve}};j(ye);const K={...o,cards:o.cards.map(xe=>xe.id===d.id?ye:xe)};M(K),d.sql&&((te=(Q=d.preferences)==null?void 0:Q.tablePrefs)!=null&&te.enableDevModePagination)&&w(!0)}function Te(ae){var Q,te,xe,pe,Fe;const ve=n.sortStateToSortByColumns(ae,(Q=d.config)==null?void 0:Q.metricColumns,(te=d.config)==null?void 0:te.groupByColumns,(xe=d.config)==null?void 0:xe.detailColumns),ye={...d,config:{...d.config||{},sortByColumns:ve}};j(ye);const K={...o,cards:o.cards.map(ee=>ee.id===d.id?ye:ee)};M(K),d.sql&&((Fe=(pe=d.preferences)==null?void 0:pe.tablePrefs)!=null&&Fe.enableDevModePagination)&&w(!0)}function Z(){var ve;const ae=JSON.stringify(V==null?void 0:V.records,null,2);typeof navigator>"u"||!((ve=navigator.clipboard)!=null&&ve.writeText)||navigator.clipboard.writeText(ae).catch(ye=>{console.error("Failed to copy JSON",ye)})}function je(){const ae=JSON.stringify(V==null?void 0:V.records,null,2),ve=new Blob([ae],{type:"application/json"}),ye=URL.createObjectURL(ve),K=document.createElement("a");K.href=ye,K.download=`${d.title}.json`,K.click()}function Ie(){const ve=[Object.keys(V==null?void 0:V.records.reduce((te,xe)=>({...te,...xe}),{})).join(","),...((V==null?void 0:V.records)||[]).map(te=>Object.values(te).join(","))].join(`
182
+ `),ye=new Blob([ve],{type:"text/csv"}),K=URL.createObjectURL(ye),Q=document.createElement("a");Q.href=K,Q.download=`${d.title}.csv`,Q.click()}if(!d)return e.jsx(e.Fragment,{children:"No Active Card"});const ne=r==="both"||r==="toolbar",Ae=r==="both"||r==="canvas";return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",r==="toolbar"?"h-auto pb-1":"h-full pt-2"),children:[ne&&e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center gap-2 px-4",children:[f&&e.jsx("div",{className:"flex grow items-center gap-4",children:e.jsx("div",{className:"flex items-center gap-3",children:!v&&!S&&e.jsx(Kn,{selectedChart:d.type,onChartChange:ae=>k(ae),compactMore:!0})})}),!z&&!_&&!q&&(V==null?void 0:V.sql)&&e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"View executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",className:"w-[500px] p-0",children:e.jsx(Wn,{sql:V.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,me&&me.length>0&&e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(n.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(n.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:me.length})]})}),e.jsxs(n.HoverCardContent,{align:"end",className:"flex max-h-[400px] w-[500px] flex-col overflow-hidden p-0",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(t.CodeEditor,{value:JSON.stringify(me,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),e.jsx(n.IconButton,{tooltip:"Refresh",disabled:z||_,className:"h-7 w-7 px-0",onClick:()=>{if(Ne(!0),x){ct.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:ie.current,exact:!0}),w(!0)},0);return}$()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":ue})})}),!S&&e.jsx(Un,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 gap-1.5 px-2 text-[12px]",a.isOpen&&"bg-muted/40 text-foreground"),children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),"Chart settings"]}),(x||y)&&i&&e.jsx(_r,{}),e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-56",children:[(x||y)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"View"}),e.jsxs(n.DropdownMenuItem,{onSelect:ae=>{ae.preventDefault(),m(!f)},className:"gap-2 text-[13px]",children:[e.jsx(t.Table2,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"flex-1",children:"Query output"}),!f&&e.jsx(t.Check,{className:"h-3.5 w-3.5 text-foreground",strokeWidth:2})]}),e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!S&&!["table","detailTable","custom"].includes(d.type)&&g&&e.jsx(jr,{triggerVariant:"menu",className:"w-full"}),e.jsx(bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Gn,{triggerVariant:"menu",className:"w-full"}),e.jsx(gs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Qn,{onCustomize:()=>N(!0)}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{onSelect:Ie,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{onSelect:je,className:"gap-2 text-[13px]",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Z,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]})]})]})]}),Ae&&(f?S?e.jsx(it,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Hn,{fallbackPreview:e.jsx(it,{}),records:de,title:d.title,isInspectorOpen:T,onInspectorOpenChange:N})}):e.jsx(it,{}):e.jsxs(n.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[b&&e.jsxs(e.Fragment,{children:[e.jsx(n.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:b&&e.jsx(zr,{})}),e.jsx(n.ResizableHandle,{})]}),e.jsxs(n.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":b}),children:[Array.isArray(V==null?void 0:V.records)&&!q&&(x?e.jsx(hr,{data:V.records,card:P,paginationMetadata:se,onPaginationChange:we,onPageSizePreferenceChange:F,onSortChange:Te,isLoading:z||_}):V.records.length>0?e.jsx(n.TableVisual,{card:d,data:de,comparisonMetadata:(Le=V==null?void 0:V.metadata)==null?void 0:Le.comparisonMetadata,paginationMetadata:se,onPaginationChange:we,onSortChange:Te,isLoading:z||_}):null),q&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ps,{error:q,errorSql:W||d.sql||d.python,onDebugWithAssistant:le,showFeedbackButton:!1})})]})]}))]})}function zr(){const s=t.useEditorStore(r=>r.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function _r(){var d,i,x,h,v,f,m,g;const s=t.useEditorStore(y=>y.card),a=t.useEditorStore(y=>y.actions.setCard),r=t.useEditorStore(y=>y.actions.setRunSql),l=t.useEditorStore(y=>y.actions.setCardPreferences),u=t.useEditorStore(y=>y.actions.updateCardInFrame),c=C.useMemo(()=>{var y,b;return n.getTablePageSizeOptions((b=(y=s.preferences)==null?void 0:y.tablePrefs)==null?void 0:b.pageSize)},[(i=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:i.pageSize]),o=n.resolveTablePageSize((h=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:h.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"dev-pagination",checked:((f=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:y=>{var b;l({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:y}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(o),onValueChange:y=>{var A,B,S;const b=Number(y),w={...s,preferences:{...s.preferences,tablePrefs:{...(A=s.preferences)==null?void 0:A.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(w),u(w),s.sql&&((S=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&S.enableDevModePagination)&&r(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(y=>e.jsx(t.SelectItem,{value:String(y),children:y},y))})]})]})}function $e({value:s,onCommit:a,type:r="text",placeholder:l,className:u}){const[c,o]=C.useState(s),d=C.useRef(!1);C.useEffect(()=>{o(s)},[s]);const i=()=>{if(d.current){d.current=!1;return}c!==s&&a(c)},x=h=>{if(h.key==="Enter"){h.currentTarget.blur();return}h.key==="Escape"&&(d.current=!0,o(s),h.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:l,value:c,onChange:h=>o(h.target.value),onBlur:i,onKeyDown:x,className:u})}function at({defaultValue:s,label:a,options:r,value:l,onValueChange:u,className:c,icon:o,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:l,onValueChange:u,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(i=>e.jsx(t.SelectItem,{value:i.value,children:i.label},i.value))]})})]})}function qr(s,a){return n.getSlotDefinitionForIndex(s,a)||null}function Tt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,l,u]=a;return`Tabs ${Number(l)+1}-${Number(u)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function $r(s){return s?Array.isArray(s)?s:[s]:[]}function ls(s){var l,u;if(!s)return!1;if(s.type==="text")return!!((l=s.description)!=null&&l.trim());const a=!!((u=s.sql)!=null&&u.trim()),r=t.hasValidCardConfig(s.config);return a||r}function Kr({slots:s,cards:a,minInputs:r}){const l=[],u=a.filter(Boolean).length;return r&&u<r&&l.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const i=a[c.position];ls(i)||l.push({type:"missing-required",message:`${Tt(c.position)} ("${c.label}") is required but has no data configured.`});return}const o=c.position.match(/^(\d+)-(\d+)$/);if(o){const[,i,x]=o.map(Number);for(let h=i;h<=x;h+=1){const v=a[h];if(!ls(v)){l.push({type:"missing-required",message:`${Tt(h)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const i=Number(d[1]);if(a.length<=i){l.push({type:"missing-required",message:`${Tt(i)} ("${c.label}") is required but has no data configured.`});return}for(let x=i;x<a.length;x+=1){const h=a[x];if(!ls(h)){l.push({type:"missing-required",message:`${Tt(x)} ("${c.label}") is required but has no data configured.`});break}}}}),a.forEach((c,o)=>{if(!c)return;const d=qr(s,o);if(!d||!d.expectedType)return;const i=$r(d.expectedType);i.length!==0&&(i.includes(c.type)||l.push({type:"wrong-type",message:`${Tt(o)} ("${d.label}") expects ${i.join(", ")}, but is configured as ${c.type}.`}))})),l}const Gr={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Jn(){var D,L,R;const s=t.useEditorStore(p=>p.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],l=t.useEditorStore(p=>p.card),u=t.useEditorStore(p=>p.frame),{setCustomCardPreferences:c}=t.useEditorActions(),o=C.useMemo(()=>n.findCustomVisualConfigCard(u,l),[u,l]),d=o==null?void 0:o.customCardPreferences,{components:i,manifest:x}=n.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),h=(D=x==null?void 0:x.visuals)==null?void 0:D.find(p=>p.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),f=n.resolveMultiInputType(o||l,h)==="multiple",m=!!o&&o.id===l.id,g=(h==null?void 0:h.minInputs)??((L=o==null?void 0:o.customCardPreferences)==null?void 0:L.minInputs),y=(h==null?void 0:h.maxInputs)??((R=o==null?void 0:o.customCardPreferences)==null?void 0:R.maxInputs),b=C.useMemo(()=>n.getCustomVisualInputCards({frame:u,configCard:o||l,isMultiInputVisual:f}),[u,o,l,f]),w=C.useMemo(()=>n.buildSlotOrderedCards(b),[b]),A=C.useMemo(()=>w.map((p,F)=>{if(!p)return null;const k=n.getSlotIndexForCard(p,F),P=n.getEffectiveCardTypeForSlot(p,k,h==null?void 0:h.slots);return{...p,type:P??p.type}}),[w,h==null?void 0:h.slots]),B=C.useMemo(()=>Kr({slots:h==null?void 0:h.slots,cards:A,minInputs:g}),[h==null?void 0:h.slots,A,g]),S=C.useMemo(()=>{const p=b.findIndex(F=>(F==null?void 0:F.id)===l.id);return p<0?-1:n.getSlotIndexForCard(l,p)},[b,l]);function E(p){if(typeof p=="number")return`Tab ${p+1}`;const F=p.match(/^(\d+)-(\d+)$/);if(F){const[,P,V]=F;return`Tabs ${Number(P)+1}-${Number(V)+1}`}const k=p.match(/^(\d+)\+$/);return k?`Tabs ${Number(k[1])+1}+`:`Tab ${p}`}function I(p){return p?(Array.isArray(p)?p:[p]).join(", "):null}function T(p,F,k=[],P="",V,z,_){const q=N({key:F,defaultValue:P,settingsValue:z,sourceCard:_});return p==="input"?e.jsx($e,{className:`h-8 w-full ${t.removeRing}`,value:String(q??""),onCommit:W=>{M({key:F,value:W,settingsField:V,settingsValue:z,sourceCard:_})}},F):p==="select"?e.jsx(at,{className:"h-8 w-full",label:"",options:k,value:String(q!==void 0?q:P??""),onValueChange:W=>{M({key:F,value:W,settingsField:V,settingsValue:z,sourceCard:_})}}):null}function N({key:p,defaultValue:F,settingsValue:k,sourceCard:P}){const V=k==null?void 0:k[p];return V!==void 0?V:p==="title"&&(P==null?void 0:P.title)!==void 0?P.title:p==="description"&&(P==null?void 0:P.description)!==void 0?P.description:F}function M({key:p,value:F,settingsField:k,settingsValue:P,sourceCard:V}){const z={...P||{}},_=p==="title"&&(V==null?void 0:V.title)!==void 0,q=p==="description"&&(V==null?void 0:V.description)!==void 0;_&&F===String((V==null?void 0:V.title)??"")||q&&F===String((V==null?void 0:V.description)??"")?delete z[p]:z[p]=F,c({...s||{},[k]:z})}function j({settingsSchema:p,settingsField:F,settingsValue:k,sourceCard:P,headerLabel:V}){const z=Object.entries(p||{});return e.jsxs("div",{className:"space-y-3",children:[V&&e.jsx(t.Label,{children:V}),z.map(([_,q])=>{var W;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:q.title}),((W=q.docs)==null?void 0:W.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:q.docs.description})})]})})]}),T(q.ui,_,q.options,q.defaultValue,F,k,P)]},_)})]})}function O(){return e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:h!=null&&h.slots&&h.slots.length>0?e.jsx("div",{className:"space-y-3",children:h.slots.map((p,F)=>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:E(p.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:p.label})]}),p.description&&e.jsx("p",{className:"text-muted-foreground",children:p.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[I(p.expectedType)&&e.jsxs("span",{children:["Expected: ",I(p.expectedType)]}),p.required&&e.jsx("span",{children:"Required"})]})]},`${p.label}-${F}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||y)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&y?" • ":"",y?`Max ${y} tabs`:""]})]})})]}),f&&B.length>0&&e.jsx(n.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(n.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((p,F)=>e.jsx("li",{children:p.message},`${p.type}-${F}`))})})}),h&&!f&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:l})})}),h&&f&&(h.settings||h.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&h.settings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:h.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||l,headerLabel:"Global Settings"})}),h.slotSettings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:h.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:l,headerLabel:(()=>{const p=l.tabTitle||l.title,F=S>=0?S:0,k=m?"Slot 0":`Slot ${F}`;return p?`${k}: ${p} Settings`:`${k} Settings`})()})})]})]})}return e.jsxs(n.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(n.AccordionItem,{value:"plugin-settings",children:[e.jsx(n.AccordionTrigger,{children:"Plugin"}),e.jsx(n.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!f||m)&&e.jsx(at,{icon:e.jsx(Ln,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(d==null?void 0:d.url)||"",onValueChange:p=>c({...s||{url:"",componentName:""},url:p})}),f&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!f||m)&&e.jsx(e.Fragment,{children:i&&e.jsx(at,{icon:e.jsx(Ca,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.map(p=>({value:p.name,label:p.name})))||[],value:s.componentName||"",onValueChange:p=>{var P;const F=(P=x==null?void 0:x.visuals)==null?void 0:P.find(V=>V.name===p),k=i==null?void 0:i.find(V=>V.name===p);c({...s,componentName:p,visualType:(F==null?void 0:F.visualType)||(k==null?void 0:k.type)||"single",minInputs:F==null?void 0:F.minInputs,maxInputs:F==null?void 0:F.maxInputs,pluginChartType:F==null?void 0:F.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(n.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(h==null?void 0:h.name)||"Settings"}),(h==null?void 0:h.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(n.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[h.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:h.docs.description}),h.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(n.Markdown,{remarkPlugins:[n.remarkGfm],components:Gr,children:h.docs.dataSchema})})]}),(()=>{var F;const p=(F=h.docs)==null?void 0:F.useCases;return!p||p.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:p.map((k,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:k})]},P))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:O()})]})]})}function Ur({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function l(o,d,i){const x=[...s];x[o]={...x[o],[d]:i},a(x)}function u(o){const d=[...s];d.splice(o,1),a(d)}function c(){a([...s,r])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(n.Plus,{className:"size-3"})})]}),s.map((o,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:i=>l(d,"start",i.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:i=>l(d,"end",i.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:i=>l(d,"color",i.target.value),value:o.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>u(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Hr(){var h,v,f,m,g;const s=t.useEditorStore(y=>y.card.preferences),a=t.useEditorStore(y=>y.actions.setCardPreferences),r=t.useEditorStore(y=>y.card),l=t.hasValidCardConfig(r.config),u=t.useEditorStore(y=>y.actions.setNumberFormat);t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.decimalPlaces});const c=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.locale}),o=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.currency});t.useEditorStore(y=>y.actions.setFilterOnClickField);const d=t.useEditorStore(y=>{var b,w;return(w=(b=y.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.colorRanges})||[],i=t.useEditorStore(y=>y.actions.setColorRanges),x=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(y=>y.currency))];return e.jsxs("div",{children:[!l&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{checked:!!((h=s==null?void 0:s.formatNumber)!=null&&h.enabled),onCheckedChange:y=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:y}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((v=s==null?void 0:s.formatNumber)==null?void 0:v.enabled)===!0||l)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:c||"none",onValueChange:y=>{var b,w,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",y,((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(y=>e.jsx(t.SelectItem,{value:y.locale,children:y.locale},y.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:y=>{var b,w,A;console.log("currency",y),u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,y==="none"?"":y,((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),x.map(y=>e.jsx(t.SelectItem,{value:y,children:y},y))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(f=s==null?void 0:s.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:y=>{var b,w,A;return u(Number(y),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((w=s==null?void 0:s.formatNumber)==null?void 0:w.locale)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(y=>e.jsx(t.SelectItem,{value:y,children:y},y))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:y=>{var b,w,A;return u(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((w=s==null?void 0:s.formatNumber)==null?void 0:w.currency)||"",((A=s==null?void 0:s.formatNumber)==null?void 0:A.locale)||"",y.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Ur,{colorRanges:d,setColorRanges:i})]})]})}const Qr={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 Yn(s){return Qr[s]}function Wr({chartType:s,showDocsLink:a=!0}){const r=Yn(s);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:r.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:r.fields.map((l,u)=>e.jsxs("tr",{className:u<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[l.name,l.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:l.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:l.description||"—"})]},l.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:r.description}),a&&r.docsUrl&&e.jsxs("a",{href:r.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:l=>l.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(n.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Jr({chartType:s}){return Yn(s)?e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(n.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Wr,{chartType:s})})]}):null}function Kt({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:a}),e.jsx(Jr,{chartType:s})]})}function Yr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Kt,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Hr,{})})]})}function bn({children:s,summary:a,open:r,className:l}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",l),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function Xn(){const[s,a]=C.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:l,setCardPreferences:u}=t.useEditorStore(x=>x.actions),c=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var h;return(h=x.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),C.useEffect(()=>{c&&a(new Array(c.length).fill(!1))},[c]);function o(x,h){var v,f;h?r!=null&&r.onClickFilter&&((v=r==null?void 0:r.onClickFilter)==null?void 0:v.length)>0?u({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):u({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(u({...r,onClickFilter:(f=r==null?void 0:r.onClickFilter)==null?void 0:f.filter(m=>m.columnIndex!==x)}),a(m=>{const g=[...m];return g[x]=!1,g}))}function d(x,h){var f;const v=(f=r==null?void 0:r.onClickFilter)==null?void 0:f.map(m=>m.columnIndex===x?{...m,expression:h.target.value}:m);u({...r,onClickFilter:v})}function i(x){var h,v,f,m;if(s!=null&&s[x]||(v=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===x))!=null&&v.expression)return e.jsx(t.Input,{value:(m=(f=r==null?void 0:r.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===x))==null?void 0:m.expression,onChange:g=>d(x,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:c==null?void 0:c.map((x,h)=>{var v,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(n.Checkbox,{checked:!!((v=r==null?void 0:r.onClickFilter)!=null&&v.find(m=>m.columnIndex===h)),onCheckedChange:m=>o(h,m)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((f=r==null?void 0:r.onClickFilter)==null?void 0:f.find(m=>m.columnIndex===h))&&e.jsx(n.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[h]=!m[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),i(h)]})},x)})})}const Xr=[{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"}],Zr=["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"],el=Zr.map(s=>({label:s,value:s}));function tl(){var i,x,h,v,f,m,g,y,b,w,A,B,S,E,I,T,N,M;const s=t.useEditorStore(j=>j.card),a=(x=(i=s==null?void 0:s.preferences)==null?void 0:i.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,l]=C.useState(((v=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:v.customTopoJsonUrl)||""),{setCardPreferences:u}=t.useEditorActions(),{data:c}=n.useTopoJson(s),o=Object.keys((c==null?void 0:c.objects)||{}).map(j=>({label:j,value:j}))||[],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(Kt,{chartType:"map"}),e.jsx(bn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(at,{className:"h-9",options:d,onValueChange:j=>{console.log("value",j),u({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:j=>{l(j.target.value)},onBlur:()=>{var j;console.log("onBlur",r),u({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.mapVisualOptions,customTopoJsonUrl:r}})},value:r,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(at,{className:"h-9",options:o,value:((m=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,objectKey:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(at,{className:"h-9",options:Xr,value:((y=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projection)||"",label:"Projection",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projection:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(at,{className:"h-9",options:el,value:((w=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(bn,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((B=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:j=>{var O;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionScale:Number(j.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=(E=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:I[0])||0,onChange:j=>{var O,D,L,R;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[Number(j.target.value),((R=(L=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(N=(T=s.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:M[1])||0,onChange:j=>{var O,D,L,R;u({...s.preferences,mapVisualOptions:{...(O=s.preferences)==null?void 0:O.mapVisualOptions,projectionOffset:[((R=(L=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:R[0])||0,Number(j.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Xn,{})]})}function Zn({color:s,onColorChange:a,onClose:r}){const[l,u]=C.useState(0),[c,o]=C.useState(100),[d,i]=C.useState(50),[x,h]=C.useState(s);C.useEffect(()=>{const b=jn(s);if(b){const w=vn(b.r,b.g,b.b);u(w.h),o(w.s),i(w.l),h(s)}},[s]);const v=b=>{u(b),m(b,c,d)},f=b=>{const w=b.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(b.clientX-w.left)/w.width)),B=Math.max(0,Math.min(1,(b.clientY-w.top)/w.height)),S=A*100,E=(1-B)*100;o(S),i(E),m(l,S,E)},m=(b,w,A)=>{const B=nl(b,w,A),S=sl(B.r,B.g,B.b);h(S)},g=b=>{if(h(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const w=jn(b);if(w){const A=vn(w.r,w.g,w.b);u(A.h),o(A.s),i(A.l)}}},y=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(a(x),r())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${l}, 100%, 50%)`},onClick:f,onMouseMove:b=>{b.buttons===1&&f(b)},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:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:l,onChange:b=>v(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:x,onChange:b=>g(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:x}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(t.Button,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(t.Button,{onClick:y,children:"OK"})]})]})}function jn(s){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function sl(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function vn(s,a,r){s/=255,a/=255,r/=255;const l=Math.max(s,a,r),u=Math.min(s,a,r);let c=0,o=0;const d=(l+u)/2;if(l!==u){const i=l-u;switch(o=d>.5?i/(2-l-u):i/(l+u),l){case s:c=((a-r)/i+(a<r?6:0))/6;break;case a:c=((r-s)/i+2)/6;break;case r:c=((s-a)/i+4)/6;break}}return{h:Math.round(c*360),s:Math.round(o*100),l:Math.round(d*100)}}function nl(s,a,r){s/=360,a/=100,r/=100;let l,u,c;if(a===0)l=u=c=r;else{const o=(x,h,v)=>(v<0&&(v+=1),v>1&&(v-=1),v<.16666666666666666?x+(h-x)*6*v:v<.5?h:v<.6666666666666666?x+(h-x)*(.6666666666666666-v)*6:x),d=r<.5?r*(1+a):r+a-r*a,i=2*r-d;l=o(i,d,s+1/3),u=o(i,d,s),c=o(i,d,s-1/3)}return{r:Math.round(l*255),g:Math.round(u*255),b:Math.round(c*255)}}const yn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],al=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function rt({value:s,onChange:a,label:r}){const[l,u]=C.useState(!1),[c,o]=C.useState(!1),d=()=>{const i=yn.find(x=>x.value===s);return i?i.color:s.startsWith("#")?s:yn[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:l,onOpenChange:u,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 ${r}`})}),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:al.map(i=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===i?"border-gray-900":"border-transparent"),style:{backgroundColor:i},onClick:()=>{a(i),u(!1)},children:e.jsx("span",{className:"sr-only",children:i})},i))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),u(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),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(Zn,{color:d(),onColorChange:i=>{a(i),o(!1)},onClose:()=>o(!1)})})]})]})}function _t(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Nn(s,a){if(!a||a==="auto")return{type:"auto"};const r={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?xs(r,_t(a)):r}function xs(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const rl=["auto","number","currency","percent","scientific","date"],ll=[{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"}],ol=[{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"}],il=s=>s.charAt(0).toUpperCase()+s.slice(1);function vt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=s.type||"auto",c=u==="auto"?s:Nn(s,u),o=m=>{m.stopPropagation()},d=(m,g)=>{a({...c,[m]:g})},[i,x]=C.useState(()=>String(c.decimalPlaces??_t(u))),[h,v]=C.useState(()=>c.multiplyBy!==void 0?String(c.multiplyBy):""),f=m=>{a(Nn(s,m))};return C.useEffect(()=>{x(String(c.decimalPlaces??_t(u)))},[c.decimalPlaces,u]),C.useEffect(()=>{v(c.multiplyBy!==void 0?String(c.multiplyBy):"")},[c.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:l}),e.jsxs(t.Select,{value:u,onValueChange:m=>f(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rl.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":il(m)},m))})]})]}),u!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(u)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:i,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");x(g),g!==""&&a(xs(c,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(i!=="")return;const m=_t(u);x(String(m)),a(xs(c,m))},className:"h-8 text-xs"})})]}),u==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ll.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(u)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ol.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),u==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(u)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>d("negativeInParentheses",m)})]}),u==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:h,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");v(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),u==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function js({value:s,onChange:a,showTitle:r=!0,title:l="NUMBER FORMAT"}){const u=t.toTFormatOptions(t.fromSemanticFormat(s))||{},c=o=>{a(t.fromTFormatOptions(o))};return e.jsx(vt,{formatOptions:u,onFormatOptionsChange:c,showTitle:r,title:l})}function cl(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:r}=t.useEditorActions(),{dashboardFilterableFields:l}=n.useFilterableFields(),{assignFilter:u}=n.useAssignFilter();function c(d){const i=u(d,"frame");r({...a,filterId:i})}const o=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(dl,{onSelect:c,columns:l}),o&&e.jsx(n.FilterHeader,{filter:o})]})}function dl({columns:s,onSelect:a}){var d;const[r,l]=zt.useState(!1),[u,c]=zt.useState(""),o=zt.useCallback(i=>[i.label,i.name,i.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:r,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":r,className:"w-full justify-between font-normal",children:[u?((d=s.find(i=>i.id===u))==null?void 0:d.label)||u:"Select Column...",e.jsx(n.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No column found."}),e.jsx(n.CommandGroup,{children:s==null?void 0:s.map(i=>e.jsxs(n.CommandItem,{value:o(i),onSelect:()=>{const x=i.id===u?"":i.id;c(x),l(!1),x&&a(i)},children:[i.label||i.name,e.jsx(n.CheckIcon,{className:t.cn("ml-auto h-4 w-4",u===i.id?"opacity-100":"opacity-0")})]},i.id))})]})]})})]})}const ul=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],ml=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function xl({cardType:s="table"}){var h,v,f,m,g;const a=t.useEditorStore(y=>y.card),r=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.preferences}),l=t.useEditorStore(y=>y.actions.setCardPreferences),u=((h=a.config)==null?void 0:h.metricColumns)||[],c=u.some(y=>y.comparisonType&&y.comparisonType!=="none"),o=((v=r==null?void 0:r.tableVisualOptions)==null?void 0:v.metricComparison)||{},d=y=>{l({...r,tableVisualOptions:{...r==null?void 0:r.tableVisualOptions,metricComparison:{...o,...y}}})},i={increase:((f=o.colors)==null?void 0:f.increase)||"green",decrease:((m=o.colors)==null?void 0:m.decrease)||"red",neutral:((g=o.colors)==null?void 0:g.neutral)||"neutral"},x=y=>{l({...r,allowDownload:y})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(n.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.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(Rn,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:o.calculatedAs||"change_difference",onValueChange:y=>d({calculatedAs:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ul.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(vt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:y=>d({formatOptions:y}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:y=>d({indicatorStyle:y}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ml.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(rt,{value:i.increase,onChange:y=>d({colors:{...i,increase:y}}),label:"Increase"}),e.jsx(rt,{value:i.decrease,onChange:y=>d({colors:{...i,decrease:y}}),label:"Decrease"}),e.jsx(rt,{value:i.neutral,onChange:y=>d({colors:{...i,neutral:y}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(n.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:y=>d({lowerIsBetter:!!y})})]})]})]}),u.length>0&&e.jsxs(n.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:u.map(y=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:y.label||y.name}),e.jsx(js,{value:y.format,onChange:b=>{var A;const w=(((A=a.config)==null?void 0:A.metricColumns)||[]).map(B=>B.id===y.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:w})},showTitle:!1})]},y.id))})]}),e.jsxs(n.AccordionItem,{value:"item-3",children:[e.jsx(n.AccordionTrigger,{children:"Click Filters"}),e.jsxs(n.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Xn,{}),e.jsx(cl,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.Checkbox,{onCheckedChange:x,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 hl(){var l;const s=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:a}=t.useEditorStore(u=>u.actions);function r(u){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:u==="dynamic"}})}return e.jsxs(n.RadioGroup,{value:(l=s==null?void 0:s.textVisualOptions)!=null&&l.isDynamicText?"dynamic":"static",onValueChange:r,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(n.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function pl(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Kt,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(hl,{})]})]})}const fl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function gl(){var E,I,T,N,M,j,O,D,L,R;const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var F;return(F=p.card)==null?void 0:F.preferences}),r=Me.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions(),c=C.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:o}=n.useEditorCardQuery(c),[d,i]=C.useState({}),[x,h]=C.useState(null),[v,f]=C.useState(null),m=C.useMemo(()=>{var P,V,z,_,q,W,$;if(!(o!=null&&o.records)||o.records.length===0)return[];const p=r==="stackedBar"||r==="stackedLine",F=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",k=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((p||F)&&k){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const U=new Set;return o.pivotSchema.forEach(se=>{se.alias&&U.add(se.alias)}),Array.from(U)}if(o.records.length>0){const U=o.records[0],se=Object.keys(U),ie=new Set;(V=s==null?void 0:s.config)!=null&&V.groupByColumns&&s.config.groupByColumns.forEach(me=>{ie.add(me.label||me.name),ie.add(me.alias||me.name)});const le=new Set;return(z=s==null?void 0:s.config)!=null&&z.metricColumns&&s.config.metricColumns.forEach(me=>{const ue=me.alias||me.name;le.add(ue),le.add(`${ue}_count`),le.add(`${ue}_sum`),le.add(`${ue}_avg`),le.add(`${ue}_min`),le.add(`${ue}_max`);const Ne=me.entityName||me.qualifiedEntityName;Ne&&(le.add(`${Ne}_${ue}`),le.add(`${Ne}_${ue}_count`))}),se.filter(me=>!ie.has(me)&&!le.has(me))}}if((F||p)&&!k&&((q=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&q.length))return s.config.metricColumns.map(U=>U.alias||U.label||U.name);if(($=(W=s==null?void 0:s.config)==null?void 0:W.groupByColumns)!=null&&$.length){const U=s.config.groupByColumns[0],se=U.label||U.name,ie=new Set;return o.records.forEach(le=>{const de=le[se];de!=null&&ie.add(String(de))}),Array.from(ie)}return[]},[o,(E=s==null?void 0:s.config)==null?void 0:E.groupByColumns,(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns,(T=s==null?void 0:s.config)==null?void 0:T.metricColumns,r]),g=C.useMemo(()=>n.getDefaultChartColors(),[]);C.useEffect(()=>{const p={};m.forEach((F,k)=>{p[F]=n.getColorForValue(F,k,a==null?void 0:a.colorConfig)}),i(p)},[m,a==null?void 0:a.colorConfig,g]);const y=(p,F)=>{const k={...d,[p]:F};i(k);const P={...a||{},colorConfig:{segments:k}};l(P);const V={...s,preferences:P};u(V)},b=(p,F)=>{var q;const k=g[F%g.length],{[p]:P,...V}=((q=a==null?void 0:a.colorConfig)==null?void 0:q.segments)||{},z={...a||{},colorConfig:{segments:V}};l(z);const _={...s,preferences:z};u(_),i(W=>({...W,[p]:k}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((M=(N=s==null?void 0:s.config)==null?void 0:N.groupByColumns)==null?void 0:M.length)||((O=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:O.length):(L=(D=s==null?void 0:s.config)==null?void 0:D.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const B=()=>{const p={...a||{},colorConfig:{segments:{}}};l(p);const F={...s,preferences:p};u(F);const k={};m.forEach((P,V)=>{k[P]=n.getColorForValue(P,V,void 0)}),i(k)},S=Object.keys(((R=a==null?void 0:a.colorConfig)==null?void 0:R.segments)||{}).length>0;return e.jsxs(n.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(n.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:S&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(ms.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((p,F)=>{const k=n.isDefaultColor(d[p],F),P=!k;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===p,onOpenChange:V=>h(V?p: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[p]}})}),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((V,z)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[p]===V?"border-gray-900":"border-transparent"),style:{backgroundColor:V},onClick:()=>{y(p,V),h(null)},children:[z===F%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:V})]},`default-${z}`))})]}),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:fl.map((V,z)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[p]===V?"border-2 border-gray-900":V==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:V},onClick:()=>{y(p,V),h(null)},children:e.jsx("span",{className:"sr-only",children:V})},`preset-${z}`))})]}),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:()=>{f({value:p,color:d[p]}),h(null)},children:"Custom color"}),!k&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(p,F),h(null)},children:[e.jsx(ms.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:p}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},p)})}),v&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>f(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Zn,{color:v.color,onColorChange:p=>{y(v.value,p),f(null)},onClose:()=>f(null)})})]})]})})]})}function Ye({value:s,onSave:a,placeholder:r="",type:l="text",className:u=""}){const[c,o]=C.useState(s??""),[d,i]=C.useState(!1);C.useEffect(()=>{o(s??"")},[s]);const x=()=>{a(c),i(!1)},h=()=>{o(s??""),i(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${u}`,children:[e.jsx(t.Input,{placeholder:r,type:l,value:d?c:s??"",onChange:v=>{o(v.target.value),i(!0)},onFocus:()=>i(!0),onClick:v=>v.stopPropagation(),className:"h-8 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.stopPropagation(),v.key==="Enter"&&d&&c!==s?x():v.key==="Escape"&&h()},"aria-label":r||"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:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function os({axis:s,label:a,type:r,config:l,onChange:u,defaultTitle:c,hidePosition:o}){var g,y,b,w,A,B,S,E,I,T,N,M,j,O;const d=n.normalizeContextFormatMode({formatMode:l==null?void 0:l.formatMode,formatOptions:l==null?void 0:l.formatOptions}),i=(D,L)=>{u({...l??{},[D]:L})},x=(D,L)=>{var k,P,V,z;const R=D==="enabled"&&L===!0,p=(k=l==null?void 0:l.name)==null?void 0:k.text,F=R&&!p&&c;u({...l??{},name:{...l==null?void 0:l.name,enabled:D==="enabled"?L:((P=l==null?void 0:l.name)==null?void 0:P.enabled)??!1,text:D==="text"?L:F?c:p,fontSize:D==="fontSize"?L:(V=l==null?void 0:l.name)==null?void 0:V.fontSize,fontWeight:D==="fontWeight"?L:(z=l==null?void 0:l.name)==null?void 0:z.fontWeight}})},h=(D,L)=>{var R,p;u({...l??{},labels:{enabled:D==="enabled"?L:((R=l==null?void 0:l.labels)==null?void 0:R.enabled)??!0,rotation:D==="rotation"?L:(p=l==null?void 0:l.labels)==null?void 0:p.rotation}})},v=(D,L)=>{u({...l??{},scale:{...l==null?void 0:l.scale,[D]:L===""?"auto":Number(L)}})},f=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(n.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(n.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-[12px] font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(t.Switch,{size:"sm",checked:(l==null?void 0:l.enabled)!==!1,onCheckedChange:D=>i("enabled",D),onClick:D=>D.stopPropagation()})]}),e.jsxs(n.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:`${s}-title-enabled`,checked:((g=l==null?void 0:l.name)==null?void 0:g.enabled)??!1,onCheckedChange:D=>x("enabled",D===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((y=l==null?void 0:l.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Ye,{placeholder:`${a} title`,value:((b=l==null?void 0:l.name)==null?void 0:b.text)||"",onSave:D=>x("text",D),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(Ye,{type:"number",placeholder:"12",value:String(((w=l==null?void 0:l.name)==null?void 0:w.fontSize)||12),onSave:D=>x("fontSize",Number(D)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((A=l==null?void 0:l.name)==null?void 0:A.fontWeight)||"normal",onValueChange:D=>x("fontWeight",D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(l==null?void 0:l.position)||"auto",onValueChange:D=>i("position",D),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:f.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"?"Auto (Default)":t.titleCase(D)},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",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((B=l==null?void 0:l.labels)==null?void 0:B.enabled)!==!1,onCheckedChange:D=>h("enabled",D)})]}),((S=l==null?void 0:l.labels)==null?void 0:S.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(((E=l==null?void 0:l.labels)==null?void 0:E.rotation)||"auto"),onValueChange:D=>h("rotation",D==="auto"?"auto":Number(D)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(D=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:D==="auto"?"Auto (Default)":`${D}°`},D))})]})]})]}),r==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:d==="override",onCheckedChange:D=>u({...l,formatMode:D?"override":"inherit"})})]}),d==="override"&&e.jsx(vt,{formatOptions:(l==null?void 0:l.formatOptions)||{},onFormatOptionsChange:D=>u({...l,formatMode:"override",formatOptions:D}),showTitle:!1})]}),r==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{type:"number",placeholder:"auto",value:((I=l==null?void 0:l.scale)==null?void 0:I.min)==="auto"||((T=l==null?void 0:l.scale)==null?void 0:T.min)===void 0?"":String(l.scale.min),onSave:D=>v("min",D),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(Ye,{type:"number",placeholder:"auto",value:((N=l==null?void 0:l.scale)==null?void 0:N.max)==="auto"||((M=l==null?void 0:l.scale)==null?void 0:M.max)===void 0?"":String(l.scale.max),onSave:D=>v("max",D),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(Ye,{type:"number",placeholder:"auto",value:((j=l==null?void 0:l.scale)==null?void 0:j.stepSize)==="auto"||((O=l==null?void 0:l.scale)==null?void 0:O.stepSize)===void 0?"":String(l.scale.stepSize),onSave:D=>v("stepSize",D),className:""})})]})]})]})]})]})}function is(s,a,r){var c,o,d;if(s==="x"){const i=(o=(c=a==null?void 0:a.config)==null?void 0:c.groupByColumns)==null?void 0:o[0];return(i==null?void 0:i.label)||(i==null?void 0:i.name)||""}const l=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],u=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const i=l.filter((x,h)=>{const v=u.find(f=>f.idx===h);return!v||v.yAxisId!=="y2"});return i.length===1&&(i[0].label||i[0].name)||""}if(s==="y2"){const i=l.filter((x,h)=>{const v=u.find(f=>f.idx===h);return(v==null?void 0:v.yAxisId)==="y2"});return i.length===1&&(i[0].label||i[0].name)||""}return""}function bl(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:l}=t.useEditorActions(),u=Me.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(u))return null;const c=n.AxisConfigurator.getAxisInfo(u,a);if(!c.hasXAxis&&!c.hasYAxis)return null;const o=(i,x)=>{let h;i==="x"?h="xAxisConfig":i==="y"?h="yAxisConfig":h="secondaryYAxisConfig";const v={...a||{},[h]:x};r(v);const f={...s,preferences:v};l(f)},d=c.hasY2Axis&&u==="combo";return e.jsxs(n.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs(n.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[c.hasXAxis&&e.jsx(os,{axis:"x",label:"X-Axis",type:c.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>o("x",i),defaultTitle:is("x",s,a)}),c.hasYAxis&&e.jsx(os,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(u,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>o("y",i),defaultTitle:is("y",s,a)}),d&&e.jsx(os,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:i=>o("y2",i),defaultTitle:is("y2",s,a),hidePosition:!0})]})})]})}function jl(){const s=t.useEditorStore(v=>v.card),a=Me.useEffectiveEditorCardType(),r=t.useEditorStore(v=>{var f,m,g,y;return(y=(g=(m=(f=v.card)==null?void 0:f.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:y.legend}),{setLegendOptions:l}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const u=n.getDefaultLegendConfig(a),c=(u==null?void 0:u.display)??!0,o=(u==null?void 0:u.position)??"top",d=(u==null?void 0:u.align)??"center",i=(v,f)=>{const m={...r,[v]:f};l(m)},x=["top","bottom","left","right"],h=["start","center","end"];return e.jsxs(n.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.display)??c,onCheckedChange:v=>i("display",v)})]}),((r==null?void 0:r.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:(r==null?void 0:r.position)||o,onValueChange:v=>i("position",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(r==null?void 0:r.align)||d,onValueChange:v=>i("align",v),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(v=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:t.titleCase(v)},v))})]})]})]})]})})]})}function vl(){var L,R,p,F,k,P,V;const s=t.useEditorStore(z=>z.card),a=Me.useEffectiveEditorCardType(),r=t.useEditorStore(z=>{var _,q;return(q=(_=z.card)==null?void 0:_.preferences)==null?void 0:q.dataLabelsConfig}),l=t.useEditorStore(z=>{var _;return(_=z.card)==null?void 0:_.preferences}),{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const o=a==="bullet"?((L=l==null?void 0:l.bulletConfig)==null?void 0:L.orientation)??(((R=l==null?void 0:l.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((p=l==null?void 0:l.chartOptions)==null?void 0:p.indexAxis)==="y",i=a==="stackedBar"||a==="stackedLine",x=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",h=a==="bubble"||a==="scatter",v=(k=(F=l==null?void 0:l.chartOptions)==null?void 0:F.plugins)==null?void 0:k.datalabels,f=(v==null?void 0:v.display)!==!1&&((v==null?void 0:v.anchor)||(v==null?void 0:v.align)),m=n.getDefaultDataLabelsConfig(a,s.preferences),g=r??m,y=(m==null?void 0:m.enabled)??f??!1,b=(r==null?void 0:r.enabled)!==void 0?r.enabled:y,w=(z,_)=>{const $={...m??{},...r??{},[z]:_};z==="enabled"&&($.display=_,_&&h&&!$.position&&($.position="bottom")),z==="position"&&h&&($.position="bottom"),z==="formatMode"&&_==="inherit"&&($.format=void 0,$.formatOptions=void 0);const U={...s.preferences||{},dataLabelsConfig:$};u(U);const se={...s,preferences:U};c(se)},A=(z,_)=>{const q=r??{},$={...m??{},...q,font:{...q.font||{},[z]:_}},U={...s.preferences||{},dataLabelsConfig:$};u(U);const se={...s,preferences:U};c(se)},B=()=>{const z=a;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":d?"right":"top"},S=a!=="treemap"&&a!=="heatmap",E=a!=="treemap",I=B();let T=[];if(S)if(h)T=["bottom"];else if(i||x)T=["center"];else{const z=d?["center","left","right"]:["center","top","bottom"];T=["auto",...a==="bullet"?z:z.filter(q=>q!==I),"custom"]}const N=()=>t.titleCase(I),M=["center","start","end"],j=["center","start","end","top","bottom"],O=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),D=(g==null?void 0:g.format)==="none";return e.jsxs(n.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(za,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:b,onCheckedChange:z=>w("enabled",z)})]}),b&&e.jsxs(e.Fragment,{children:[S&&!i&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:h?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:z=>w("position",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:z==="auto"?N():z==="custom"?"Custom (Advanced)":t.titleCase(z)},z))})]})]}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.showTotal)??!1,onCheckedChange:z=>w("showTotal",z)})]}),(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:z=>w("anchor",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]}),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:z=>w("align",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:j.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:t.titleCase(z)},z))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:O==="override",onCheckedChange:z=>w("formatMode",z?"override":"inherit")})]}),O==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:D,onCheckedChange:z=>{const _=r??{},W={...m??{},..._,formatMode:"override",format:z?"none":void 0,formatOptions:z?void 0:_.formatOptions},$={...s.preferences||{},dataLabelsConfig:W};u($),c({...s,preferences:$})}})]}),!D&&e.jsx(vt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:z=>{const W={...m??{},...r??{},formatMode:"override",format:z.type&&z.type!=="auto"?z.type:void 0,formatOptions:z},$={...s.preferences||{},dataLabelsConfig:W};u($),c({...s,preferences:$})},showTitle:!1})]})]}),E&&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(Ye,{type:"number",placeholder:"12",value:String(((P=g==null?void 0:g.font)==null?void 0:P.size)||12),onSave:z=>A("size",Number(z)),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:((V=g==null?void 0:g.font)==null?void 0:V.weight)||"normal",onValueChange:z=>A("weight",z),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:z=>{z==="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(Ye,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:z=>w("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Cn={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
183
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function yl(){var f,m,g,y,b,w,A,B,S,E;const s=t.useEditorStore(I=>I.card),{setCardPreferences:a}=t.useEditorActions(),r=Me.useEffectiveEditorCardType(),l=((f=s.config)==null?void 0:f.metricColumns)||[],u=((m=s.config)==null?void 0:m.groupByColumns)||[],c=l.length===2&&u.length===0,o=l.some(I=>I.comparisonType&&I.comparisonType!=="none");if(!(r==="kpi"&&(c||o)))return null;const i=((y=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:y.metricComparison)||{},x=I=>{var N;const T={...s.preferences,kpiVisualOptions:{...(N=s.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...i,...I}}};a(T)},h=o||i.enabled,v=l.some(I=>I.comparisonType==="previous_period"||I.comparisonType==="same_period_last_year"||I.comparisonType==="start_vs_end");return e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rn,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&l.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:i.enabled||!1,onCheckedChange:I=>x({enabled:I,...I&&!i.calculationType?{calculationType:"difference"}:{}})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const I=i.calculationType||"difference",T=Cn[I];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:T==null?void 0:T.label}),e.jsx("p",{children:T==null?void 0:T.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:T==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",T==null?void 0:T.example]})]})})()})]})]}),e.jsxs(t.Select,{value:i.calculationType||"difference",onValueChange:I=>x({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(Cn).map(([I,T])=>e.jsx(t.SelectItem,{value:I,className:"text-xs",children:T.label},I))})]})]}),e.jsx(vt,{formatOptions:i.formatOptions||{},onFormatOptionsChange:I=>x({formatOptions:I}),showTitle:!0,title:"COMPARISON FORMAT"}),(v||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:i.position||"right",onValueChange:I=>x({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(n.Checkbox,{id:"show-arrow",checked:i.showArrow!==!1,onCheckedChange:I=>x({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(n.Checkbox,{id:"show-color",checked:i.showColor!==!1,onCheckedChange:I=>x({showColor:I})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),i.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(rt,{value:((b=i.colorConfig)==null?void 0:b.increase)||"green",onChange:I=>x({colorConfig:{...i.colorConfig,increase:I}}),label:"Primary > Secondary"}),e.jsx(rt,{value:((w=i.colorConfig)==null?void 0:w.decrease)||"red",onChange:I=>x({colorConfig:{...i.colorConfig,decrease:I}}),label:"Primary < Secondary"}),e.jsx(rt,{value:((A=i.colorConfig)==null?void 0:A.noChange)||"neutral",onChange:I=>x({colorConfig:{...i.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(n.Checkbox,{id:"conditional-label",checked:i.conditionalLabel||!1,onCheckedChange:I=>x({conditionalLabel:I})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),i.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((B=i.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:I=>x({conditionalLabels:{...i.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:((S=i.conditionalLabels)==null?void 0:S.decrease)??"Decrease",onChange:I=>x({conditionalLabels:{...i.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:((E=i.conditionalLabels)==null?void 0:E.noChange)??"No change",onChange:I=>x({conditionalLabels:{...i.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:i.labelName??"",onChange:I=>x({labelName:I.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Nl(){var c;const s=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),a=t.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const l=((c=a==null?void 0:a.chartOptions)==null?void 0:c.treemapColorMode)??"branch",u=o=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:o}};r(d)};return e.jsxs(n.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(n.RadioGroup,{value:l,onValueChange:o=>u(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const Cl=Object.keys(n.HEATMAP_PRESET_PALETTES);function Sl(){const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var m;return(m=f.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),l=(s==null?void 0:s.type)==="heatmap",u=(a==null?void 0:a.heatmapConfig)||{},c=u.colorPalette??"green",o=u.legendPosition??"bottom",d=C.useMemo(()=>u.colorRange&&u.colorRange[0]&&u.colorRange[1]?[u.colorRange[0],u.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[u.colorRange]),i=f=>{const m={...u,...f};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:m})},x=f=>{i({colorPalette:f,colorRange:f==="custom"?u.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},h=(f,m)=>{const g=[...d];g[f]=m,i({colorPalette:"custom",colorRange:g})},v=f=>{i({legendPosition:f})};return l?e.jsxs(n.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(n.RadioGroup,{value:c,onValueChange:f=>x(f??"blue"),className:"space-y-3",children:[Cl.map(f=>{const m=n.HEATMAP_PRESET_PALETTES[f];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`heatmap-${f}`,value:f}),e.jsxs(t.Label,{htmlFor:`heatmap-${f}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},f)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(rt,{value:d[0],onChange:f=>h(0,f),label:"Start color"}),e.jsx(rt,{value:d[1],onChange:f=>h(1,f),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:f=>v(f??"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(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:f[0].toUpperCase()+f.slice(1)},f))})]})]})]})]}):null}const Sn=["poor","satisfactory","good"];function wn(s){if(!s)return;const a={...s};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function wl(){var L,R;const s=t.useEditorStore(p=>p.card.preferences),a=t.useEditorStore(p=>p.card),r=t.useEditorStore(p=>p.isDevMode),{setCardPreferences:l,setChartOrientation:u}=t.useEditorActions(),c=C.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,[i,x]=C.useState(c.showRanges??!1),[h,v]=C.useState(c.rangesArePercentages??!1),f=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[m,g]=C.useState(f);C.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),C.useEffect(()=>{v(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const y=c.targetValue===void 0?"":String(c.targetValue);C.useEffect(()=>{const p=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;g(p)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const b=C.useMemo(()=>{var p,F;return((F=(p=a==null?void 0:a.config)==null?void 0:p.metricColumns)==null?void 0:F.map(k=>{const P=k.label||k.name||k.alias||"";return{value:P,label:P}}))||[]},[(L=a==null?void 0:a.config)==null?void 0:L.metricColumns]);C.useEffect(()=>{var q,W;if(!s||b.length===0)return;const p={};let F=!1;const k=(q=b[1])==null?void 0:q.value;!c.targetMetricKey&&k&&(p.targetMetricKey=k,F=!0);const P=(W=b[2])==null?void 0:W.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&P&&(p.comparativeMetricKey=P,F=!0);const V=b.slice(3),z={...c.rangeKeys||{}};let _=!1;if(Sn.forEach(($,U)=>{!z[$]&&V[U]&&(z[$]=V[U].value,_=!0)}),_&&(p.rangeKeys=z,F=!0,c.showRanges===void 0&&(p.showRanges=!0)),F){const $=wn({...c,...p});l({...s,bulletConfig:$})}},[b,c,s,l]);const w=p=>{const F=wn({...c,...p});l({...s,bulletConfig:F})},A=(p,F)=>{const k={...c.rangeKeys||{},[p]:F.trim()};F.trim()||delete k[p],w({rangeKeys:Object.keys(k).length>0?k:void 0})},B=(p,F)=>{const k=F===""?void 0:Number(F),P={...c.ranges||{}};k===void 0||Number.isNaN(k)?delete P[p]:P[p]=k,w({ranges:Object.keys(P).length?P:void 0})},S=p=>{if(p===""){w({targetValue:void 0});return}const F=Number(p);w({targetValue:Number.isNaN(F)?void 0:F})},E=(p,F)=>{const k=F.trim(),P={...c.rangeLabels||{}};k?P[p]=k:delete P[p],w({rangeLabels:Object.keys(P).length>0?P:void 0})},I=p=>{x(p),w({showRanges:p})},T=p=>{v(p),w({rangesArePercentages:p})},N=c.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),M=p=>{w({orientation:p}),u(p==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(p=>({value:p.value,label:p.label}))],O=j,D=p=>{if(g(p),!p){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){w({disableAutoComparative:!1});return}if(c.comparativeMetricKey)w({disableAutoComparative:!1});else{const F=b.find(k=>k.value!==c.targetMetricKey);w({comparativeMetricKey:F==null?void 0:F.value,disableAutoComparative:!1})}};return e.jsxs(n.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:N,onValueChange:p=>M(p),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:p=>w({targetMetricKey:p==="__none"?void 0:p}),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"}),b.map(p=>e.jsx(t.SelectItem,{value:p.value,className:"text-xs",children:p.label},p.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(t.Select,{value:c.comparativeMetricKey||"__none",onValueChange:p=>w({comparativeMetricKey:p==="__none"?void 0:p,disableAutoComparative:p==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:j.map(p=>e.jsx(t.SelectItem,{value:p.value,className:"text-xs",children:p.label},p.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:p=>D(p)})]}),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($e,{type:"number",className:"h-8 text-xs",value:y,onCommit:S,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(t.Switch,{size:"sm",checked:i,onCheckedChange:I})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:h,disabled:!i,onChange:p=>T(p.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),i&&e.jsx("div",{className:"space-y-3",children:Sn.map(p=>{var F,k,P,V,z;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," LABEL"]}),e.jsx($e,{placeholder:`Display label (${p})`,value:((F=c.rangeLabels)==null?void 0:F[p])||"",onCommit:_=>E(p,_),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," COLUMN"]}),e.jsxs(t.Select,{value:((k=c.rangeKeys)==null?void 0:k[p])||"__none",onValueChange:_=>{_==="__none"?A(p,""):A(p,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:O.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:[p," COLUMN KEY"]}),e.jsx($e,{placeholder:"Column key",value:((P=c.rangeKeys)==null?void 0:P[p])||"",onCommit:_=>A(p,_),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[p," VALUE"]}),e.jsx($e,{type:"number",placeholder:h?"0.80":"Static value",value:((V=c.ranges)==null?void 0:V[p])===void 0?"":String((z=c.ranges)==null?void 0:z[p]),onCommit:_=>B(p,_),className:"h-8 text-xs"})]})]},p)})})]})]})]})}function Tn(s){if(!s)return;const a={...s};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Tl(){var E,I,T,N,M,j,O,D,L,R,p,F;const s=t.useEditorStore(k=>k.card.preferences),a=t.useEditorStore(k=>k.card),r=Me.useEffectiveEditorCardType(),l=t.useEditorStore(k=>k.isDevMode),{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions(),o=r==="bubble",d=r==="scatter",i=C.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),h=t.hasValidCardConfig(a==null?void 0:a.config)&&!l,v=C.useMemo(()=>{var k,P;return((P=(k=a==null?void 0:a.config)==null?void 0:k.metricColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(E=a==null?void 0:a.config)==null?void 0:E.metricColumns]),f=C.useMemo(()=>{var k,P;return((P=(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns)==null?void 0:P.map(V=>{const z=V.label||V.name||V.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.groupByColumns]),m=C.useMemo(()=>i.enableGrouping!==void 0?i.enableGrouping:!l&&f.length>=2,[i.enableGrouping,l,f.length]),[g,y]=C.useState(m);C.useEffect(()=>{y(m)},[m]);const b=k=>{const P={...s||{},bubbleScatterConfig:k};u(P),a&&c({...a,preferences:P})},w=k=>{u(k),a&&c({...a,preferences:k})};C.useEffect(()=>{if(!s||v.length===0)return;const k={};let P=!1;if(!i.xMetricKey&&v[0]&&(k.xMetricKey=v[0].value,P=!0),!i.yMetricKey&&v[1]&&(k.yMetricKey=v[1].value,P=!0),o&&!i.radiusMetricKey&&v[2]&&(k.radiusMetricKey=v[2].value,P=!0),!i.labelKey&&f[0]&&(k.labelKey=f[0].value,P=!0),m&&!i.groupKey&&f[1]&&(k.groupKey=f[1].value,k.enableGrouping=!0,P=!0),P){const V=Tn({...i,...k});b(V)}},[v,f,i,s,u,o,m]);const A=k=>{const P=Tn({...i,...k});b(P)},B=k=>{y(k),A({enableGrouping:k,groupKey:k?i.groupKey:void 0})};if(!o&&!d)return null;const S=o?n.Circle:n.ChartScatter;return e.jsxs(n.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Label Column"}),h?e.jsxs(t.Select,{value:i.labelKey||"",onValueChange:k=>A({labelKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for labels",value:i.labelKey||"",onCommit:k=>A({labelKey:k})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),h?e.jsxs(t.Select,{value:i.groupKey||"",onValueChange:k=>A({groupKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:f.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:i.groupKey||"",onCommit:k=>A({groupKey:k})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Axis"}),h?e.jsxs(t.Select,{value:i.xMetricKey||"",onValueChange:k=>A({xMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:i.xMetricKey||"",onCommit:k=>A({xMetricKey:k})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),h?e.jsxs(t.Select,{value:i.yMetricKey||"",onValueChange:k=>A({yMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:i.yMetricKey||"",onCommit:k=>A({yMetricKey:k})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),h?e.jsxs(t.Select,{value:i.radiusMetricKey||"",onValueChange:k=>A({radiusMetricKey:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:v.map(k=>e.jsx(t.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx($e,{className:"h-8 text-xs",placeholder:"Column name for radius",value:i.radiusMetricKey||"",onCommit:k=>A({radiusMetricKey:k})})]})]}),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:i.radiusScale||"sqrt",onValueChange:k=>A({radiusScale:k}),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"})]})]})]}),i.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($e,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((T=i.minRadius)==null?void 0:T.toString())||"",onCommit:k=>A({minRadius:k?Number(k):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx($e,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((N=i.maxRadius)==null?void 0:N.toString())||"",onCommit:k=>A({maxRadius:k?Number(k):void 0})})]})]}),i.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",i.fixedRadius||10]}),e.jsx(n.Slider,{value:[i.fixedRadius||10],onValueChange:([k])=>A({fixedRadius:k}),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: ",i.fixedRadius||5]}),e.jsx(n.Slider,{value:[i.fixedRadius||5],onValueChange:([k])=>A({fixedRadius:k}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(t.Switch,{size:"sm",checked:((j=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:j.enabled)??!1,onCheckedChange:k=>{var z,_,q,W;const P=i.xMetricKey||"X Axis",V=i.yMetricKey||"Y Axis";w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:k,text:((_=(z=s==null?void 0:s.xAxisConfig)==null?void 0:z.name)==null?void 0:_.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:k,text:((W=(q=s==null?void 0:s.yAxisConfig)==null?void 0:q.name)==null?void 0:W.text)||V}}})}})]}),((D=(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name)==null?void 0:D.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:i.xMetricKey||"X Axis",value:((R=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:R.text)||"",onCommit:k=>{var P;w({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:k||i.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx($e,{className:"h-8 text-xs",placeholder:i.yMetricKey||"Y Axis",value:((F=(p=s==null?void 0:s.yAxisConfig)==null?void 0:p.name)==null?void 0:F.text)||"",onCommit:k=>{var P;w({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:k||i.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const El=[{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 Il(){const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var m;return(m=f.card)==null?void 0:m.preferences}),{setCardPreferences:r}=t.useEditorActions(),l=(s==null?void 0:s.type)==="funnel",u=(a==null?void 0:a.funnelConfig)||{},c=u.percentMode??"percentOfTotal",o=u.shrinkFraction??1,d=u.labelThreshold??0,i=f=>{const m={...u,...f};r({...a||{},funnelConfig:m})},x=f=>{i({percentMode:f})},h=f=>{i({shrinkFraction:f[0]})},v=f=>{i({labelThreshold:f[0]})};return l?e.jsxs(n.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(n.RadioGroup,{value:c,onValueChange:f=>x(f),className:"space-y-2",children:El.map(f=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`funnel-${f.value}`,value:f.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${f.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:f.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]},f.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(n.Slider,{value:[o],onValueChange:h,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(n.Slider,{value:[d],onValueChange:v,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function Gt(){const s=t.useEditorStore(c=>c.card),{data:a}=n.useEditorCardQuery(s),{keys:r}=n.getKeys((a==null?void 0:a.records)||[]),l=r.slice(1).filter(c=>!t.METADATA_KEYS.includes(c));let u=l;if(["stackedBar","stackedLine"].includes(s.type)){const c=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:r[0],pivotKey:r[1],valueKey:r[2]}),{keys:o}=n.getKeys(c);u=o.slice(1)}return{transformedMetricKeys:u,dimensionKeys:r.slice(0,1),keys:r,defaultMetricKeys:l}}const kl=[{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"}],Dl=[{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)"}],Al=["center","start","end"],Ml=["center","start","end","top","bottom"];function Ut({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:l=!0,positionOptions:u,showAppearance:c=!0}){var g,y,b,w,A,B;const o=u??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=l?["auto","number","currency","percent","none"]:["number","currency","percent","none"],i=(S,E)=>{const I={...s,[S]:E};a(I)},x=(S,E)=>{const I={...s,font:{...(s==null?void 0:s.font)||{},[S]:E}};a(I)},h=(S,E)=>{const I={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:E}};a(I)},v=()=>r?"Right":"Top",f=s||{},m=f.format||(l?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:f.position||"auto",onValueChange:S=>i("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?v():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),f.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:f.anchor||"center",onValueChange:S=>i("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]}),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(f.align||"center"),onValueChange:S=>i("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:S=>i("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&l?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Ye,{type:"number",placeholder:"0",value:String(((g=f.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:S=>h("decimalPlaces",Number(S)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((y=f.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:S=>h("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((b=f.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:S=>h("useSuffix",S)})]}),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=f.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:S=>h("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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(Ye,{type:"number",placeholder:"12",value:String(((A=f.font)==null?void 0:A.size)||12),onSave:S=>x("size",Number(S)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((B=f.font)==null?void 0:B.weight)||"normal",onValueChange:S=>x("weight",S),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:f.color==="auto"||!f.color?"auto":"custom",onValueChange:S=>{S==="auto"&&i("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(Ye,{type:"number",placeholder:"0",value:String(f.rotation||0),onSave:S=>i("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Ll=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Fl=[0,1,2,3,4,5,6,8,10],Rl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Ol=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Pl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(n.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Bl,{})})]})}function Bl(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(Vl,{metricKey:a,idx:r},a))})}function Vl({metricKey:s,idx:a}){var w;const[r,l]=C.useState(!1),u=t.useEditorStore(A=>{var B;return(B=A.card)==null?void 0:B.preferences}),c=t.useEditorStore(A=>{var B,S;return(S=(B=A.card)==null?void 0:B.preferences)==null?void 0:S.datasetOptions}),o=c==null?void 0:c.find(A=>A.idx===a),{setCardPreferences:d}=t.useEditorStore(A=>A.actions),i=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",h=((w=o==null?void 0:o.dataLabels)==null?void 0:w.enabled)??!1,v=i==="line"?n.ChartLine:n.ChartColumnIncreasing;function f(A){const B={idx:a,type:i,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...A};if(!o)d({...u||{},datasetOptions:[...c||[],B]});else{const S=c==null?void 0:c.map(E=>E.idx===a?{...E,...B}:E);d({...u||{},datasetOptions:S})}}function m(A){f({type:A})}function g(A){f({yAxisId:A})}function y(A){f({dataLabels:{...o==null?void 0:o.dataLabels,enabled:A}})}function b(A){f({dataLabels:A})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(v,{className:"h-3 w-3"}),i==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Ll.map(({type:A,icon:B,label:S})=>{const E=i===A;return e.jsxs("button",{onClick:()=>m(A),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",E?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:S})]},A)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:x,onValueChange:A=>g(A),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),i==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:A=>f({lineStyle:A}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ol.map(({value:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},A))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:A=>f({pointRadius:Number(A)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Fl.map(A=>e.jsx(t.SelectItem,{value:String(A),className:"text-xs",children:A===0?"None":A},A))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:A=>f({pointStyle:A}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Rl.map(({value:A,label:B})=>e.jsx(t.SelectItem,{value:A,className:"text-xs",children:B},A))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:y})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const cs=[{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"}],zl=[0,1,2,3,4,5,6,8,10],_l=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],ql=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function $l(s){return s==null?"origin":s===!1?"false":s}function Kl(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(n.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Gl,{})})]})}function Gl(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(Ul,{metricKey:a,idx:r},a))})}function Ul({metricKey:s,idx:a}){var y;const[r,l]=C.useState(!1),u=t.useEditorStore(b=>{var w;return(w=b.card)==null?void 0:w.preferences}),c=t.useEditorStore(b=>{var w,A;return(A=(w=b.card)==null?void 0:w.preferences)==null?void 0:A.datasetOptions}),o=c==null?void 0:c.find(b=>b.idx===a),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),i=$l(o==null?void 0:o.fill),x=((y=o==null?void 0:o.dataLabels)==null?void 0:y.enabled)??!1,h=cs.find(b=>b.value===i)||cs[0];function v(b){const w={idx:a,fill:i,dataLabels:o==null?void 0:o.dataLabels,...b};if(!o)d({...u||{},datasetOptions:[...c||[],w]});else{const A=c==null?void 0:c.map(B=>B.idx===a?{...B,...w}:B);d({...u||{},datasetOptions:A})}}function f(b){v({fill:b==="false"?!1:b})}function m(b){v({dataLabels:{...o==null?void 0:o.dataLabels,enabled:b}})}function g(b){v({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(n.ChartArea,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:i,onValueChange:b=>f(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cs.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.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:b=>v({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},b))})]})]}),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:b=>v({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:zl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),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:b=>v({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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.Switch,{size:"sm",checked:x,onCheckedChange:m})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Hl=[0,1,2,3,4,5,6,8,10],Ql=[{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 │"}],ds=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Wl(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="line"?null:e.jsxs(n.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(Jl,{})})]})}function Jl(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(Yl,{metricKey:a,idx:r},a))})}function Yl({metricKey:s,idx:a}){var b;const[r,l]=C.useState(!1),u=t.useEditorStore(w=>{var A;return(A=w.card)==null?void 0:A.preferences}),c=t.useEditorStore(w=>{var A,B;return(B=(A=w.card)==null?void 0:A.preferences)==null?void 0:B.datasetOptions}),o=c==null?void 0:c.find(w=>w.idx===a),{setCardPreferences:d}=t.useEditorStore(w=>w.actions),i=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,h=(o==null?void 0:o.pointStyle)||"circle",v=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,f=ds.find(w=>w.value===i)||ds[0];function m(w){const A={idx:a,lineStyle:i,pointRadius:x,pointStyle:h,dataLabels:o==null?void 0:o.dataLabels,...w};if(!o)d({...u||{},datasetOptions:[...c||[],A]});else{const B=c==null?void 0:c.map(S=>S.idx===a?{...S,...A}:S);d({...u||{},datasetOptions:B})}}function g(w){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:w}})}function y(w){m({dataLabels:w})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(n.TrendingUp,{className:"h-3 w-3"}),f.label.split(" ")[0]]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:i,onValueChange:w=>m({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ds.map(({value:w,label:A})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:A},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(x),onValueChange:w=>m({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:Hl.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:h,onValueChange:w=>m({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(({value:w,label:A})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:A},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.Switch,{size:"sm",checked:v,onCheckedChange:g})]}),v&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:o==null?void 0:o.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Xl=[0,2,4,6,8,10,12,16,20];function Zl(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(n.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(eo,{})})]})}function eo(){const{transformedMetricKeys:s}=Gt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((a,r)=>e.jsx(to,{metricKey:a,idx:r},a))})}function to({metricKey:s,idx:a}){var g;const[r,l]=C.useState(!1),u=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.type}),c=t.useEditorStore(y=>{var b;return(b=y.card)==null?void 0:b.preferences}),o=t.useEditorStore(y=>{var b,w;return(w=(b=y.card)==null?void 0:b.preferences)==null?void 0:w.datasetOptions}),d=o==null?void 0:o.find(y=>y.idx===a),{setCardPreferences:i}=t.useEditorStore(y=>y.actions),x=(d==null?void 0:d.borderRadius)??0,h=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function v(y){const b={idx:a,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...y};if(!d)i({...c||{},datasetOptions:[...o||[],b]});else{const w=o==null?void 0:o.map(A=>A.idx===a?{...A,...b}:A);i({...c||{},datasetOptions:w})}}function f(y){v({dataLabels:{...d==null?void 0:d.dataLabels,enabled:y}})}function m(y){v({dataLabels:y})}return e.jsx(n.Collapsible,{open:r,onOpenChange:l,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(n.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(x),onValueChange:y=>v({borderRadius:Number(y)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(y=>e.jsx(t.SelectItem,{value:String(y),className:"text-xs",children:y===0?"None":`${y}px`},y))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:h,onCheckedChange:f})]}),h&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ut,{config:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:u==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const so=[0,1,2,3,4,5,6,8,10],no=[{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 │"}],ao=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ro(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var i;return(i=d.card)==null?void 0:i.preferences}),r=Me.useEffectiveEditorCardType(),l=a==null?void 0:a.lineStyleConfig,{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const o=(d,i)=>{const x={...a||{},lineStyleConfig:{...l,[d]:i}};u(x),c({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:d=>o("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ao.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:d=>o("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:so.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:d=>o("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:no.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]})]})})]})}const lo=[0,2,4,6,8,10,12,16,20],oo=[{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%"}],io=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function co(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var i;return(i=d.card)==null?void 0:i.preferences}),r=Me.useEffectiveEditorCardType(),l=a==null?void 0:a.barStyleConfig,{setCardPreferences:u,updateCardInFrame:c}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const o=(d,i)=>{const x={...a||{},barStyleConfig:{...l,[d]:i}};u(x),c({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.borderRadius)??0),onValueChange:d=>o("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:lo.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.barPercentage)??.9),onValueChange:d=>o("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:oo.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((l==null?void 0:l.categoryPercentage)??.8),onValueChange:d=>o("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:io.map(({value:d,label:i})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:i},d))})]})]})]})})]})}function uo(){const s=t.useEditorStore(r=>{var l,u;return(u=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:u.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(n.AccordionItem,{value:"stacked-sort",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(n.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(at,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})})]})}const mo=["kpi"],En={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},us=2;function ot(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 xo(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const a=t.getDataType(s.dataType);return["date","string","boolean"].includes(a)}function ho(s){return{...s,role:"groupby"}}function po(){var A,B;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),r=Me.useEffectiveEditorCardType(),{scopedFields:l}=n.useScopedFields(),u=((A=s.config)==null?void 0:A.metricColumns)||[],c=((B=s.config)==null?void 0:B.summary)||{},o=c.breakdownDimensions||[],d=mo.includes(r),i=u.length>0,x=c.enabled===!0,h=d&&i,{comparisonType:v}=n.getEffectiveComparisonSettings(s.config,r),f=En[v]||En.none,m=Array.from(new Map(l.filter(xo).map(S=>[ot(S),ho(S)])).values()),g=new Set(m.map(S=>ot(S))),y=new Set(o.map(S=>ot(S)).filter(S=>S&&g.has(S)));if(!d)return null;const b=S=>{a(s.id,{summary:{...c,...S}})},w=(S,E)=>{const I=ot(S),T=m.filter(M=>y.has(ot(M))),N=E?y.has(I)?T:[...T,S].slice(0,us):T.filter(M=>ot(M)!==I);b({breakdownDimensions:N})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!i&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:x,disabled:!h,onCheckedChange:S=>{if(!S){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({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: ",f]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!x,onCheckedChange:S=>b({showOnCard:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:S=>b({includeInDashboardSummary:S})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",us]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(S=>{const E=ot(S),I=y.has(E),T=y.size>=us,N=!x||!I&&T;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${E}`,checked:I,disabled:N,onCheckedChange:M=>w(S,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${E}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},E)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!x,onCheckedChange:S=>b({anomalyEnabled:S})})]})]})]})}const fo=[];function go(){var u;const s=t.useEditorStore(c=>c.card),a=((u=s==null?void 0:s.config)==null?void 0:u.metricColumns)??fo,{updateMetricColumn:r,updateCardInFrame:l}=t.useEditorActions();return!s||s.type==="kpi"||a.length===0?null:e.jsxs(n.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An.Braces,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 pt-2",children:a.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(js,{value:c.format,onChange:o=>{var d;r(s.id,c.id,{format:o}),l({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(i=>i.id===c.id?{...i,format:o}:i)}})}})]},c.id))})]})}const bo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function jo(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),r=Me.useEffectiveEditorCardType(),{setCardPreferences:l,updateCardInFrame:u}=t.useEditorActions();if(!s||!bo.has(r||""))return null;const c=a==null?void 0:a.tooltipConfig,o=(c==null?void 0:c.formatMode)||(c==null?void 0:c.mode)||"inherit",d=i=>{const x={...a||{},tooltipConfig:{...c||{},...i}};l(x),u({...s,preferences:x})};return e.jsxs(n.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.Switch,{size:"sm",checked:o==="override",onCheckedChange:i=>d({formatMode:i?"override":"inherit",mode:i?"override":"inherit"})})]}),o==="override"&&e.jsx(vt,{formatOptions:(c==null?void 0:c.formatOptions)||{},onFormatOptionsChange:i=>d({formatMode:"override",mode:"override",formatOptions:i}),showTitle:!1})]})]})}function ea({mode:s}){const a=t.useEditorStore(r=>{var l;return(l=r.card)==null?void 0:l.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Pl,{}),(a==="area"||a==="stackedArea")&&e.jsx(Kl,{}),a==="line"&&e.jsx(Wl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(Zl,{}),e.jsx(ro,{}),e.jsx(co,{}),e.jsx(Nl,{}),s==="config"&&e.jsx(yl,{}),s==="config"&&e.jsx(po,{}),e.jsx(Sl,{}),a==="bullet"&&e.jsx(wl,{}),a==="funnel"&&e.jsx(Il,{}),(a==="bubble"||a==="scatter")&&e.jsx(Tl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(uo,{}),e.jsx(go,{}),e.jsx(gl,{}),e.jsx(bl,{}),e.jsx(jl,{}),e.jsx(vl,{}),e.jsx(jo,{})]})}function vo(){const s=t.useEditorStore(r=>r.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Kt,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(ea,{mode:"dev"})})]}):null}function yo(){const s=t.useEditorStore(u=>u.card),a=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(n.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(n.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(n.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function l(){switch(a){case"kpi":return e.jsx(Yr,{});case"table":return e.jsx(xl,{});case"map":return e.jsx(tl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Jn,{})});case"text":return e.jsx(pl,{});default:return e.jsx(vo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[l(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function No(){const s=C.useRef(null),a=C.useRef(null),r=t.useEditorStore(g=>g.isShowingVisual),l=t.useEditorStore(g=>g.isDevMode),u=t.useEditorStore(g=>g.showAIDialog),[c,o]=C.useState(!1),d=r&&!u,i=d&&(!l||c),x=l&&d,h=()=>o(g=>!g);C.useEffect(()=>{var g,y,b,w;u?((g=s.current)==null||g.resize(0),(y=a.current)==null||y.resize(0)):((b=s.current)==null||b.resize(25),(w=a.current)==null||w.resize(25))},[u]);const[v,f]=C.useState(!1),m=x?{show:!0,isOpen:c,onToggle:h}:void 0;return e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(n.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:50,children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(ur,{})}),e.jsx(rs,{mode:"toolbar",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})]})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:i?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(rs,{mode:"canvas",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})}),!u&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(yo,{})})]}):e.jsx(rs,{mode:"canvas",visualAsideControl:m,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:f})})]})}function Co(s){var ye;t.useAIInteractionStore(K=>K.currentAIContext);const[a,r]=C.useState(""),[l,u]=C.useState(null),{authToken:c,tokenProps:o}=n.useSemaphorContext(),d=t.useEditorStore(K=>K.card.id),i=t.useEditorStore(K=>{var Q;return(Q=K==null?void 0:K.card)==null?void 0:Q.sql}),x=t.useEditorStore(K=>K.isDevMode),h=t.useEditorStore(K=>{var Q;return(Q=K==null?void 0:K.card)==null?void 0:Q.python}),{setCardPython:v,setCardSql:f,setRunSql:m,switchCardType:g,setQueryConfig:y}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],w=t.useEditorStore(K=>K.userInputForAI),A=t.useEditorStore(K=>K.triggerAIRun),B=t.useEditorStore(K=>K.card),S=t.useEditorStore(K=>K.selectedDatabaseName),E=t.useEditorStore(K=>K.selectedTableName),I=t.useEditorStore(K=>K.selectedConnectionId),T=t.useEditorStore(K=>K.selectedSchemaName),N=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:M,refetch:j,data:O}=n.useEditorCardQuery(B),{setTriggerAIRun:D,setCurrentAssitantScope:L,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:p,connectionType:F,selectedDatamodelId:k}=n.useEditorAside(),P=(ye=n.useDashboardQuery().data)==null?void 0:ye.assistantProfileId,V=C.useRef(n.createAssistantConversationId()),z=C.useRef(null),_=C.useRef(d),q=C.useRef(!1),W=()=>{const K=z.current;K&&(z.current=null,V.current=n.createAssistantConversationId(),K==="clear"&&U([]))},{messages:$,setMessages:U,regenerate:se,error:ie,sendMessage:le,status:de,addToolResult:me,stop:ue,clearError:Ne}=n.useChat({transport:new n.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:V.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:x,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:Q})=>({body:{...Q,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var Q;if(q.current=!1,K.name==="AbortError"||(Q=K.message)!=null&&Q.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),W();return}console.error("[Editor Assistant] Stream error:",K),W()},onToolCall:je,onFinish({isAbort:K,isDisconnect:Q,isError:te}){q.current=!1,r(""),console.log(K?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":te?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),W()}}),we=C.useCallback(K=>{q.current=!0;try{const Q=le(K);return n.isPromiseLike(Q)?Q.catch(te=>{throw q.current=!1,te}):Q}catch(Q){throw q.current=!1,Q}},[le]),Te=C.useCallback(()=>{q.current=!0;try{const K=se();return n.isPromiseLike(K)?K.catch(Q=>{throw q.current=!1,Q}):K}catch(K){throw q.current=!1,K}},[se]),Z=K=>{let Q=!1;U(te=>{const xe=typeof K=="function"?K(te):K;if(xe.length===0){if(q.current)return z.current="clear",Q=!0,te;z.current=null,V.current=n.createAssistantConversationId()}return xe}),Q&&ue()};C.useEffect(()=>{if(_.current!==d){if(_.current=d,q.current){z.current!=="clear"&&(z.current="rotate"),ue();return}z.current=null,V.current=n.createAssistantConversationId()}},[d,ue]),C.useEffect(()=>{A&&w&&(we({role:"user",parts:[{type:"text",text:w}]}),D(!1))},[A,w,we,D]);async function je({toolCall:K}){var Q,te,xe,pe,Fe,ee,Se,fe,De,Oe,Qe,Ke,Ge,re,ke,ze;if(["createChartFromSql","createForecast"].includes(K.toolName)){const Ce=((Q=K.input)==null?void 0:Q.sql)??((te=K.args)==null?void 0:te.sql),We=((xe=K.input)==null?void 0:xe.python)??((pe=K.args)==null?void 0:pe.python),Ee=((Fe=K.input)==null?void 0:Fe.chartType)??((ee=K.args)==null?void 0:ee.chartType);g(Ee),f(Ce),v(We),m(!0),me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!i){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:i,python:h||""}})}else if(K.toolName==="generateQueryConfig"){r("Generating query config...");const Ce=((Se=K.input)==null?void 0:Se.chartType)??((fe=K.args)==null?void 0:fe.chartType),We=((De=K.input)==null?void 0:De.queryConfig)??((Oe=K.args)==null?void 0:Oe.queryConfig);((Qe=K.input)==null?void 0:Qe.cardConfig)??((Ke=K.args)==null||Ke.cardConfig),g(Ce),R(We),f(void 0),v(void 0);const Ee=await j();if((Ge=Ee==null?void 0:Ee.data)!=null&&Ge.error){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:We,message:(re=Ee==null?void 0:Ee.data)==null?void 0:re.error.message}});return}if((ke=Ee==null?void 0:Ee.data)!=null&&ke.records){me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:We,message:"The data has been visualized"}});return}me({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:We,message:"The data has been visualized",records:(ze=Ee==null?void 0:Ee.data)==null?void 0:ze.records}})}else r("Analyzing...")}function Ie(K){const Q=n.removeFromScopeArray(b,K);ne(Q)}function ne(K){const Q=n.sanitizeAIScope(K);L(Q),U(te=>[...te,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}]}])}function Ae(){const K={databaseName:S||"",schemaName:T||"",tableName:E||"",datamodelId:k||"",datamodelName:t.resolveDatamodelName(p),connectionId:I||"",connectionType:F||""},Q=n.dedup([...b,K]);ne(Q)}function Le(){const K={databaseName:S||"",schemaName:T||"",tableName:E||"",datamodelName:t.resolveDatamodelName(p),connectionId:I||"",connectionType:F||"",datamodelId:k||""};if(!n.isInAiScopeArray([...N||[],...b],K)||b.length===0){const te=n.dedup([...N||[],...b,K]).filter(xe=>xe.connectionId===K.connectionId);ne(te)}}const ae=!["ready","error"].includes(de),ve=n.getErrorMessage(ie);return{messages:$,setMessages:Z,sendMessage:we,regenerate:Te,isLoading:ae,handleSetAIScope:Le,handleAddCurrentTableToScope:Ae,removeFromCurrentSelections:Ie,currentAssitantScope:b,setCurrentAssitantScope:L,stop:ue,status:de,toolStatus:a,llmUsage:l,onFinish:s,errorMessage:ve,clearError:Ne}}const So=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function In({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const l=C.useRef(null),u=C.useRef(!1),[c,o]=C.useState(!1),[d,i]=C.useState(t.isDevEnv),[x,h]=C.useState(!1),[v,f]=C.useState(!1),[m,g]=C.useState(!1),y=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:w,setHasEditorEntitySelectionOverride:A}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:S}=t.useFileActions(),E=t.useFileAttachments("editor"),{selectedEntities:I}=n.useAssistantContextEntities("editor"),T=t.useEditorStore(re=>re.card.id),N=t.useEditorStore(re=>re.card.dataSource),M=t.useEditorStore(re=>{var ke;return(ke=re.card.dataSource)==null?void 0:ke.selectedEntities}),j=t.useEditorStore(re=>re.actions.setCardSql),O=t.useEditorStore(re=>re.actions.setRunSql),D=t.useEditorStore(re=>re.showAIDialog),L=t.useDashboardStore(re=>re.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:p}=t.useEditorActions(),{setDataSource:F}=t.useEditorActions(),{assistantProfile:k}=n.useAssistantProfile(),{messages:P,setMessages:V,sendMessage:z,isLoading:_,stop:q,status:W,llmUsage:$,errorMessage:U,clearError:se}=Co(),[ie,le]=C.useState(""),de=re=>{le(re.target.value)},me=re=>{re.preventDefault();const ke=ie.trim();if(!ke&&E.length===0)return;const ze=[];ke&&ze.push({type:"text",text:ke}),E.forEach(Ce=>{Ce.data&&ze.push({type:"file",mediaType:Ce.type,filename:Ce.name,url:`data:${Ce.type};base64,${Ce.data}`})}),z({role:"user",parts:ze}),le(""),S("editor"),ae({force:!0})},{visibleMessages:ue,hasMoreMessages:Ne,totalMessageCount:we,loadMoreMessages:Te,resetMessageWindow:Z}=n.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:je,contentRef:Ie,isAtBottom:ne,hasNewMessages:Ae,newMessageCount:Le,scrollToBottom:ae,handleScroll:ve,resetNewMessageCount:ye}=n.useAutoScroll(ue,{threshold:40,behavior:"smooth",isStreaming:_});C.useEffect(()=>{var re;D&&!u.current&&((re=l.current)==null||re.focus()),u.current=D},[D]),C.useEffect(()=>{D&&(A(!1),w({selectedEntities:M||[]}))},[T,M,w,A,D]),n.useAutoSubmitQueue({assistantType:"editor",status:W,isLoading:_,sendMessage:z});const{hasActiveTools:K,activeToolText:Q}=n.useActiveToolStatus(P),te=C.useCallback(re=>{a==null||a(re),s===void 0&&g(re)},[s,a]);C.useEffect(()=>{if(!y)return;function re(ke){ke.key==="Escape"&&te(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[y,te]);const xe=C.useCallback(re=>{z({role:"user",parts:[{type:"text",text:re}]}),ae({force:!0})},[z,ae]),pe=C.useCallback(async()=>{const re=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),n.ue.success("Conversation copied")}catch(ke){console.error("Failed to copy conversation",ke),n.ue.error("Unable to copy conversation")}},[P]),Fe=C.useCallback(()=>{te(!y)},[y,te]);function ee(re,ke){ke==="sql"?(j(re),O(!0)):ke==="python"&&(p(re),O(!0))}function Se(){b.selectedEntities.length===0&&w({selectedEntities:I})}function fe(re){Se();const ke={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};z(ke)}function De(re){Se(),z({role:"user",parts:[{type:"text",text:re}]})}function Oe(){return e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(n.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",children:[e.jsx(n.DropdownMenuLabel,{children:"Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Token Usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:h,children:"System Message"})]})]})}function Qe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ke=(ie==null?void 0:ie.length)===0&&(P==null?void 0:P.filter(re=>re.role==="user").length)===0,Ge=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Qe(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Oe(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:pe,children:"Copy Conversation"}),e.jsx(n.IconButton,{tooltip:y?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Fe,children:y?e.jsx(n.Minimize2,{className:"size-4"}):e.jsx(n.Maximize2,{className:"size-4"})}),e.jsx(n.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{V([]),B("editor"),se(),Z()},children:e.jsx(n.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(n.CustomScrollArea,{ref:je,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:ve,children:e.jsxs("div",{ref:Ie,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[Ne&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:Te,className:"text-xs",children:["Load ",Math.min(5,we-ue.length)," ","more messages (",we-ue.length," ","hidden)"]})}),e.jsx(n.PrintMessages,{messages:ue,showTools:d,handleRun:ee,showSystemMessage:x,onQuickReply:xe,disableQuickReplies:_}),e.jsx(n.AssistantStatus,{status:W,errorMessage:U,activeToolText:_&&K?Q:void 0})]})}),D&&!ne&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{ae({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),Ae&&Le>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:Le>9?"9+":Le})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ke&&!k&&e.jsx(n.Placeholders,{onClick:fe,placeholders:So}),e.jsx("div",{children:Ke&&k&&e.jsx(n.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:De})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:l,setInput:le,stop:q,input:ie,handleInputChange:de,handleSubmit:re=>{Se(),me(re),ae({force:!0})},isLoading:_,status:W,assistantType:"editor",onFocus:()=>{}})]}),$&&c&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",$.inputTokens," prompt tokens, ",$.outputTokens," ","completion tokens, ",$.totalTokens," total tokens"]})}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:I,open:v,onOpenChange:f,dataSource:N||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:re=>{A(!0),w({...b,selectedEntities:re})}})]});return y&&r?ja.createPortal(e.jsx(n.SemaphorStyleWrapper,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:Ge})}),r):Ge}function wo(s,a,r){if(!a)return!1;const l=a.qualifiedFieldName,u=a.qualifiedEntityName,c=u&&a.name?`${u}.${a.name}`:l;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const i=n.getSelectedDateFilterColumn(o,r),x=i.split("."),h=x[x.length-1]||i,v=x.length>1?x.slice(0,-1).join("."):void 0,f=o.qualifiedTableName||v,m=f?`${f}.${h}`:void 0;return l?m?m===c||m.endsWith(`.${l}`):h===a.name:m?m===c:h===a.name})}function To({aliasTemplate:s,onAliasTemplateChange:a}){var i;const[r,l]=C.useState(s),[u,c]=C.useState(!1),o=(i=t.useEditorStore(x=>{var h;return(h=x.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:i[0],d=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:d,value:u?r:s,onChange:x=>{l(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&u&&r!==s?(a(r),c(!1)):x.key==="Escape"&&(l(s),c(!1))},"aria-label":"Edit alias template"}),u&&r!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(r),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:()=>{l(s),c(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Eo({valueAliases:s,onValueAliasesChange:a}){const[r,l]=C.useState(null),[u,c]=C.useState(""),[o,d]=C.useState(""),i=()=>{a({...s,"":""})},x=v=>{const f={...s};delete f[v],a(f)},h=v=>{const f={...s};delete f[v],f[u]=o,a(f),l(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([v,f],m)=>e.jsx("div",{className:"flex items-center gap-2",children:r===v?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:u,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:o,onChange:g=>d(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(v):g.key==="Escape"&&l(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(v),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>l(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:v,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{l(v),c(v),d(f)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{l(v),c(v),d(f)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(v),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},v+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:i,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Io({idx:s}){var d;const a=t.useEditorStore(i=>{var x;return(x=i.card)==null?void 0:x.preferences}),r=t.useEditorStore(i=>{var x;return(x=i.card.preferences)==null?void 0:x.datasetOptions}),l=t.useEditorStore(i=>i.actions.setCardPreferences),u=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,c=r==null?void 0:r.find(i=>i.idx===s);function o(i,x){(i==="end"||i==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:i!=="none",align:i,anchor:i,clamp:!0};if(!c)l({...a,datasetOptions:[...r||[],{idx:x,datalabels:h}]});else{const v={...c};v.datalabels=h;const f=r==null?void 0:r.map(m=>m.idx===x?v:m);l({...a,datasetOptions:f})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Va,{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(Ia,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ka,{className:t.cn("h-4 w-4",{"rotate-90":u==="y"})})})]})})]})}function vs({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ko(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Do({col:s,idx:a,className:r,iconClassName:l,children:u}){const c=t.useEditorStore(h=>{var v;return(v=h.card)==null?void 0:v.preferences}),o=t.useEditorStore(h=>{var v,f;return(f=(v=h.card)==null?void 0:v.preferences)==null?void 0:f.datasetOptions}),d=o==null?void 0:o.find(h=>h.idx===a),{setCardPreferences:i}=t.useEditorStore(h=>h.actions);function x(h){if(!d)i({...c,datasetOptions:[...o||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const v={...d};v.type=h==="area"?"line":h,v.fill=h==="area"?"origin":"";const f=o==null?void 0:o.map(m=>m.idx===a?v:m);i({...c,datasetOptions:f})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[u||e.jsx(vs,{className:"max-w-[100px]",title:s,children:ko(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(n.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",l)}),e.jsx(Io,{idx:a})]})]})}function Ao(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),r=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:l}=t.useEditorStore(d=>d.actions);function u(d){var h;const i={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(h=r==null?void 0:r.chartOptions)==null?void 0:h.plugins,...i}}};l(x)}function c(){var d,i,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(i=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:i.datalabels)==null?void 0:x.anchor)||"none",onValueChange:u,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function o(){var d,i,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(i=(d=r==null?void 0:r.chartOptions)==null?void 0:d.plugins)==null?void 0:i.datalabels)==null?void 0:x.anchor)||"none",onValueChange:u,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?c():o()})}function Mo({column:s}){const a=t.useEditorStore(i=>i.card.type),r=t.useEditorStore(i=>{var x,h;return(h=(x=i.card)==null?void 0:x.config)==null?void 0:h.metricColumns}),l=(r==null?void 0:r.map(i=>i.label))||[],u=l==null?void 0:l.find(i=>i===s.label||i===s.name),c=u?l.indexOf(u):-1;function o(){return e.jsx("div",{className:"pr-1",children:u&&e.jsx(Do,{idx:c,col:u,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ao,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&o(),["pie","doughnut"].includes(a)&&d()]})}function Lo({field:s,searchQuery:a="",limit:r=500}){const{authToken:l,tokenProps:u}=n.useSemaphorContext(),c=t.useEditorStore(x=>x.card),o=c==null?void 0:c.dataSource,d=["attribute-values",s.entityName,s.name,a,r],i=n.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:r},h={connection_id:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:t.getCacheConfig({card:c})};console.log("requestBody",h);const v=await t.postRequestRegular(`${u.apiServiceUrl}/v1/query`,(l==null?void 0:l.accessToken)||"",h);if(v!=null&&v.error)return console.error("Error fetching attribute values:",v.error),[];const f=s.name;return((v==null?void 0:v.records)||[]).map(g=>{const y=g[f]||g[s.alias||f]||g[s.label];return{id:y||"",value:y||"",label:String(y||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function ta({open:s,onOpenChange:a,availableFields:r,existingFilters:l,editingCondition:u,onSave:c}){var B,S;const o=!!u,[d,i]=C.useState(o?"values":"fields"),[x,h]=C.useState(""),[v,f]=C.useState({id:(u==null?void 0:u.id)||t.v4(),field:(u==null?void 0:u.field)||null,selectedValues:u?Array.isArray(u.value)?u.value:[u.value]:[]}),m=r.filter(E=>{var T;return o?!1:!((T=l==null?void 0:l.conditions)==null?void 0:T.some(N=>N.field.id===E.id))&&E.label.toLowerCase().includes(x.toLowerCase())}),g=E=>{f({...v,field:E}),i("values")},y=()=>{if(v.field&&v.selectedValues.length>0){const E={id:v.id,field:v.field,operator:"in",value:v.selectedValues};let I;if(o){const T=((l==null?void 0:l.conditions)||[]).map(N=>N.id===u.id?E:N);I={...l,conditions:T}}else{const T=(l==null?void 0:l.conditions)||[];I={id:(l==null?void 0:l.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...T,E],groups:[]}}c(I),a(!1)}},b=()=>{if(!o||!u)return;const E=((l==null?void 0:l.conditions)||[]).filter(I=>I.id!==u.id);if(E.length>0){const I={...l,conditions:E};c(I)}else c(void 0);a(!1)},w=E=>{f({...v,selectedValues:E})},A=()=>{o&&u?(f({id:u.id,field:u.field,selectedValues:Array.isArray(u.value)?u.value:[u.value]}),i("values")):(f({id:t.v4(),field:null,selectedValues:[]}),i("fields")),h("")};return C.useEffect(()=>{s&&A()},[s,o,u]),e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-2xl",children:[e.jsx(n.DialogHeader,{children:e.jsx(n.DialogTitle,{children:o?`Edit Filter: ${(B=v.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(S=v.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(l==null?void 0:l.conditions)&&l.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.conditions.map(E=>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:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),d==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(n.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:x,onChange:E=>h(E.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),x&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>h(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:m.map(E=>e.jsxs("button",{type:"button",onClick:()=>g(E),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(n.IconForFieldType,{dataType:t.getDataType(E.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:E.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),m.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),m.length===0&&!x&&r.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Fo,{field:v.field,selectedValues:v.selectedValues,onValuesChange:w,onBack:o?void 0:()=>i("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:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:A,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:y,disabled:!v.field||v.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Fo({field:s,selectedValues:a,onValuesChange:r,onBack:l}){const[u,c]=C.useState(""),{values:o,isLoading:d,isFetching:i}=Lo({field:s,searchQuery:u,limit:500}),x=u?o.filter(f=>String(f.value).toLowerCase().includes(u.toLowerCase())):o,h=f=>{const m=a.includes(f);r(m?a.filter(g=>g!==f):[...a,f])},v=()=>{a.length===x.length&&x.length>0?r([]):r(x.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:l,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(n.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:u,onChange:f=>c(f.target.value),className:"pl-10"})]}),d||i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(n.Checkbox,{checked:a.length===x.length&&x.length>0,onCheckedChange:v}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>h(f.value),children:[e.jsx(n.Checkbox,{checked:a.includes(f.value),onCheckedChange:()=>h(f.value)}),e.jsx(vs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function Ro({field:s,zone:a,index:r,sortDirection:l,onSortDirectionChange:u,hasPivotColumns:c=!1,cardType:o}){var Es,Is,ks,Ds,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Ws,Js,Ys,Xs,Zs,en,tn,sn,nn,an,rn;const{attributes:d,listeners:i,setNodeRef:x,transform:h,transition:v,isDragging:f}=n.useSortable({id:s.id}),m=t.useEditorStore(H=>H.card),g=t.useEditorStore(H=>H.frame),y=t.useDashboardStore(H=>H.isVisualEditing),b=t.useDashboardStore(H=>H.selectedSheetId),w=t.useDashboardStore(H=>H.actions.updateSheetCalculatedFields),{scopedFields:A,valuePickFilterableFields:B,isLoading:S}=n.useFilterableFields(),{userContext:E}=n.useCurrentUserInfo(),I=(E==null?void 0:E.type)==="organization",{updateLabel:T,handleAggregationChange:N,handleDateFormatChange:M,handleGranularityChange:j,handleAliasTemplateChange:O,handleValueAliasesChange:D,handleMetricFormatChange:L,removeField:R,handleMetricComparisonChange:p,handleMetricWindowTransformChange:F,handleMetricWindowOrderByChange:k,handleMetricWindowDirectionChange:P,handleMetricWindowPartitionToggle:V,handleMetricMovingAverageWindowSizeChange:z,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:q,handleMetricPercentOfTotalScopeChange:W,handleMetricPercentOfTotalOutputChange:$,handleKpiShowTrendlineChange:U,handleKpiTrendlineWindowChange:se,handleKpiTrendlineGranularityChange:ie,handleMetricTargetValueChange:le}=n.useFieldManagement(m),[de,me]=C.useState(!1),[ue,Ne]=C.useState(()=>{var H;return!!((H=s.parameters)!=null&&H.windowTransform)}),[we,Te]=C.useState(!1),[Z,je]=C.useState(!1),[Ie,ne]=C.useState(null),Ae=C.useMemo(()=>{const H=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Y=H(s.id),he=A.find(oe=>{if(s.qualifiedFieldName&&oe.qualifiedFieldName&&oe.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&oe.qualifiedEntityName&&oe.qualifiedEntityName===s.qualifiedEntityName&&oe.name===s.name)return!0;const Re=H(oe.id);return!!(Y&&Re&&Y===Re)});return{dataType:(he==null?void 0:he.dataType)||s.dataType,resolvedFromScopedField:!!he}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,A]),Le=n.getGranularityOptionsForFieldType(Ae.dataType),[ae,ve]=C.useState(s.dateFormat||"YYYY-MM-DD"),[ye,K]=C.useState(s.customFormat||""),[Q,te]=C.useState(!!s.customFormat),xe=C.useRef(null),[pe,Fe]=C.useState(s.aliasTemplate||""),[ee,Se]=C.useState(s.valueAliases||{}),[fe,De]=C.useState((Es=s.parameters)==null?void 0:Es.filters),Oe=H=>{H==="custom"?te(!0):(te(!1),ve(H),(a==="groupBy"||xt)&&M(r,H,"",a))},Qe=H=>{K(H),(a==="groupBy"||xt)&&M(r,"custom",H,a)},Ke=H=>{var oe;const he=(oe=n.getDateFormatOptionsForGranularity(H)[0])==null?void 0:oe.value;he&&!Q&&(ve(he),a==="groupBy"&&M(r,he,"",a)),a==="groupBy"&&j(r,H)},Ge=H=>{Fe(H),a==="metrics"&&O(r,H)},re=H=>{Se(H),a==="metrics"&&D(r,H)},ke=H=>{T(a,r,H)},ze=n.getExpressionFieldKind(s),Ce=n.getFieldExpressionAnnotation(s),We=n.isManagedCalculatedExpressionField(s),Ee=s.role==="metric"&&We,yt=We&&(ze==="user_calculated"||ze==="inline_expression"&&s.fieldScope!=="domain"),Ze=yt?(Is=g==null?void 0:g.calculatedFields)==null?void 0:Is.find(H=>t.matchesCalculatedField(H,s,{allowComparableFallback:!0})):void 0,kt=yt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Ze),Je=ze==="domain_calculated"||s.fieldScope==="domain",Dt=Je?n.resolveDomainCalculatedFieldForEdit(s,A):void 0,dt=Je?"domain":kt?"dashboard":"card",et=Je?Dt||s:kt&&Ze?Ze:s,At=H=>{var Y;if(De(H),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:H}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}Te(!1)},Nt=()=>{R(a,r)},Ht={transform:n.CSS.Transform.toString(h),transition:v},Mt=t.getDataType(Ae.dataType||s.dataType),ut=Mt==="date",mt=o==="kpi",xt=a==="detailColumns",ht=(ks=m.config)==null?void 0:ks.metricColumns,Ue=(Ds=m.config)==null?void 0:Ds.groupByColumns,tt=t.useDashboardStore(H=>{var Y;return(Y=H.dashboard)==null?void 0:Y.filters}),Qt=t.useDashboardStore(H=>H.filterValues),st=s.granularity||"day",Lt=Le.includes(st)?st:"day",Ct=a==="groupBy"&&!Le.includes(st),pt=n.getDateFormatOptionsForGranularity(Lt),Wt=Q?"custom":pt.some(H=>H.value===ae)?ae:((As=pt[0])==null?void 0:As.value)??"YYYY-MM-DD";C.useEffect(()=>{var he;if(S||!Ct){xe.current=null;return}const H=`${s.id}:${st}:${Ae.dataType||s.dataType||""}:${r}`;if(xe.current===H)return;xe.current=H;const Y="day";if(j(r,Y),!Q){const oe=(he=n.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:he.value;oe&&(ve(oe),M(r,oe,"",a))}},[s.dataType,s.id,M,j,Ct,r,Q,S,st,Ae.dataType,a]);const Jt=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Yt=o==="kpi"||o==="table",He=C.useMemo(()=>Ue==null?void 0:Ue.find(H=>t.getDataType(H.dataType||"")==="date"),[Ue]),Ft=C.useMemo(()=>(Ue||[]).some(H=>t.getDataType(H.dataType||"")==="date"),[Ue]),ft=C.useMemo(()=>{var oe;if(!He)return!1;const H=(oe=m.config)==null?void 0:oe.filters;if(!H)return!1;const Y=Re=>{const Be=Re.field;return Be?He.id&&Be.id===He.id||He.qualifiedFieldName&&Be.qualifiedFieldName===He.qualifiedFieldName?!0:Be.name===He.name:!1},he=Re=>Re.conditions.some(qe=>t.getDataType(qe.field.dataType||"")==="date"&&Y(qe))?!0:Re.groups.some(qe=>he(qe));return he(H)},[(Ms=m.config)==null?void 0:Ms.filters,He]),Rt=C.useMemo(()=>wo(tt||[],He,Qt),[tt,Qt,He]),St=ft||Rt,G=s,X=((Fs=(Ls=G.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.function)||"none",J=n.isMetricTransformEnabled(G),ce=J?X:null,ge=n.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:m.config||{},metric:G,transformMode:ce||"running_total"}),be=!!G.comparisonType&&G.comparisonType!=="none",Pe=n.getRunningTotalOrderByCandidates(Ue||[]),Ve=((Ps=(Os=(Rs=G.parameters)==null?void 0:Rs.windowTransform)==null?void 0:Os.orderBy)==null?void 0:Ps.fieldId)||"",Xe=((zs=(Vs=(Bs=G.parameters)==null?void 0:Bs.windowTransform)==null?void 0:Vs.orderBy)==null?void 0:zs.direction)||"asc",lt=Pe.find(H=>H.id===Ve),nt=ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta",_e=J&&nt&&!!lt&&t.getDataType(lt.dataType||"")!=="date",gt=n.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:m.config||{},orderByFieldId:Ve||void 0}),Xt=new Set(((qs=(_s=G.parameters)==null?void 0:_s.windowTransform)==null?void 0:qs.partitionByFieldIds)||gt),Zt=o==="pivotTable"||n.isSubtotalEnabledAggregateTable(o||"table",m.config||{}),Ns=[...(Ue||[]).filter(H=>H.id&&(!nt||H.id!==Ve)),...Zt?((($s=m.config)==null?void 0:$s.pivotByColumns)||[]).filter(H=>H.id):[]],Cs=((Us=(Gs=(Ks=G.parameters)==null?void 0:Ks.windowTransform)==null?void 0:Gs.movingAverage)==null?void 0:Us.windowSize)||7,na=((Ws=(Qs=(Hs=G.parameters)==null?void 0:Hs.windowTransform)==null?void 0:Qs.movingAverage)==null?void 0:Ws.minPeriods)||1,aa=((Xs=(Ys=(Js=G.parameters)==null?void 0:Js.windowTransform)==null?void 0:Ys.previousPeriodDelta)==null?void 0:Xs.mode)||"absolute",Ss=((tn=(en=(Zs=G.parameters)==null?void 0:Zs.windowTransform)==null?void 0:en.percentOfTotal)==null?void 0:tn.scope)||"grand_total",ra=((an=(nn=(sn=G.parameters)==null?void 0:sn.windowTransform)==null?void 0:nn.percentOfTotal)==null?void 0:an.output)||"percent",la=C.useMemo(()=>(ht||[]).some(H=>H.comparisonType==="start_vs_end"),[ht]);C.useEffect(()=>{J&&Ne(!0)},[J]);const oa=a!=="pivotBy"&&a!=="sortBy",ia=ut&&a==="groupBy"&&(!mt||la),ca=!mt&&ut&&(a==="groupBy"||xt),da=o==="kpi"&&ut&&a==="groupBy",ua=a==="metrics",ws=Jt&&a==="metrics",ma=()=>{const H=s,Y=a==="metrics"&&Ee;return e.jsxs("div",{className:"space-y-1",children:[!Y&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:he=>{he.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Y&&H.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(H.calculatedFormula),onPointerDown:he=>{he.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",n.formatDisplayFormula(H.calculatedFormula)]})]})},xa=()=>oa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ye,{value:s.label??"",onSave:ke,placeholder:"Display label...",type:"text"})]}):null,ha=()=>a!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:l||"asc",onValueChange:H=>u(H),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),Ts=()=>ia?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:Lt,onValueChange:Ke,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:Le.map(H=>e.jsx(t.SelectItem,{className:"text-xs",value:H,children:t.toTitleCase(H)},H))})]})]}):null,pa=()=>ca?e.jsxs(e.Fragment,{children:[Ts(),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:Wt,onValueChange:Oe,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:pt.map(H=>e.jsx(t.SelectItem,{className:"text-xs",value:H.value,children:H.label},H.value))})]}),Q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:ye,onChange:H=>{H.stopPropagation(),Qe(H.target.value)},onClick:H=>H.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,fa=()=>{var Y,he,oe,Re;const H=da;return H?e.jsx(e.Fragment,{children:H&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:U})]})}),((he=m.config)==null?void 0:he.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input,{type:"number",min:"1",max:"365",value:((oe=m.config)==null?void 0:oe.trendlineWindow)||30,onChange:Be=>{const qe=parseInt(Be.target.value)||30;se(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:((Re=m.config)==null?void 0:Re.trendlineGranularity)||"day",onValueChange:ie,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},ga=()=>{if(!ua)return null;const H=Ee;return e.jsxs(e.Fragment,{children:[H&&I&&!Je&&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:()=>je(!0),children:[e.jsx(n.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Y=>{N(r,Y)},disabled:H,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(js,{value:G.format,onChange:Y=>L(r,Y),showTitle:!1})]}),e.jsx(n.Collapsible,{open:ue,onOpenChange:Ne,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!ue&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(X.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",ue?"rotate-180":"")})]})]})}),e.jsxs(n.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:J?X:"none",onValueChange:Y=>F(r,Y),disabled:!ge.supported&&!J,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:be,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:be,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:be,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:be,children:"Percent of Total"})]})]}),!ge.supported&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ge.reason}),be&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&e.jsxs(e.Fragment,{children:[nt&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:Ve,onValueChange:Y=>k(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Pe.filter(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Ve&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),_e&&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:Xe,onValueChange:Y=>P(r,Y),disabled:!Ve,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),ce==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input,{type:"number",min:1,className:"h-8 text-xs",value:Cs,onChange:Y=>z(r,Number(Y.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:Cs,className:"h-8 text-xs",value:na,onChange:Y=>_(r,Number(Y.target.value))})]}),ce==="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:aa,onValueChange:Y=>q(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),ce==="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:Ss,onValueChange:Y=>W(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:ra,onValueChange:Y=>$(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(ce==="running_total"||ce==="moving_average"||ce==="previous_period_delta"||ce==="percent_of_total"&&Ss==="partition_total")&&Ns.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:Ns.map(Y=>{const he=!!Y.id&&Xt.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&V(r,Y.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",he?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Y.label||Y.name}),he?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.id)})})]})]})]})]})}),ws&&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:G.comparisonType||"none",disabled:J,onValueChange:Y=>p(r,Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Y=!Ft||!St,he=Ft?St?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(Re,Be)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Re,disabled:Y,title:he,children:Be})}),Y&&he&&e.jsx(t.TooltipContent,{side:"right",children:he})]})});return e.jsxs(e.Fragment,{children:[oe("previous_period","Previous Period"),oe("same_period_last_year","Same Period Last Year"),oe("start_vs_end","Start vs End")]})})(),Yt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),ws&&G.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input,{type:"number",value:G.targetValue!==void 0&&G.targetValue!==null?String(G.targetValue):"",onChange:Y=>{const he=Y.target.value;if(he===""){le(r,void 0);return}const oe=Number(he);le(r,Number.isFinite(oe)?oe: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"}),(fe==null?void 0:fe.conditions)&&fe.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:fe.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{ne(Y),Te(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((he,oe)=>e.jsx("div",{children:String(he)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:he=>{var Re;he.stopPropagation();const oe=fe.conditions.filter(Be=>Be.id!==Y.id);if(oe.length>0){const Be={...fe,conditions:oe};At(Be)}else if(De(void 0),a==="metrics"){const Be={...s,parameters:{...s.parameters,filters:void 0}},qe=[...((Re=m.config)==null?void 0:Re.metricColumns)||[]];qe[r]=Be,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:qe})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{ne(null),Te(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Mo,{column:s}),c&&e.jsxs(e.Fragment,{children:[e.jsx(To,{aliasTemplate:pe,onAliasTemplateChange:Ge}),e.jsx(Eo,{valueAliases:ee,onValueAliasesChange:re})]})]})};fe!=null&&fe.conditions&&fe.conditions.length>0;const ba=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:de,onOpenChange:me,children:[e.jsxs("div",{ref:x,style:Ht,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",de?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",f&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...d,...i,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${n.getMetricDisplayLabel(s)}`,onClick:H=>{H.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:Mt,calculated:!!Ce}),e.jsx(vs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((rn=fe==null?void 0:fe.conditions)==null?void 0:rn.length)&&!de&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(n.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:fe.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:fe.conditions.map(H=>e.jsxs("div",{children:[H.field.label,":"," ",Array.isArray(H.value)?`${H.value.length} values`:String(H.value)]},H.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":l==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:H=>{H.stopPropagation(),u(l==="asc"?"desc":"asc")},children:l==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),ba&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:H=>H.stopPropagation(),children:e.jsx(n.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:H=>{H.stopPropagation(),Nt()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[ma(),ha(),xa(),o==="kpi"&&Ts(),pa(),fa(),ga()]})})]}),we&&e.jsx(ta,{open:we,onOpenChange:H=>{Te(H),H||ne(null)},availableFields:B,existingFilters:fe,editingCondition:Ie,onSave:H=>{var Y;if(H)At(H);else if(De(void 0),a==="metrics"){const he={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[r]=he,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}ne(null)}}),Z&&a==="metrics"&&Ee&&e.jsx(n.CalculatedFieldEditor,{open:Z,onOpenChange:je,availableFields:A,existingField:et,existingFieldScope:dt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:H=>{var Pt;if(H.role!=="metric")return;const{card:Y,frame:he,actions:oe}=t.useEditorStore.getState(),Re=((Pt=Y.config)==null?void 0:Pt.metricColumns)||[],Be=he.calculatedFields||[],{nextActiveFields:qe,nextStoredFields:wt,nextSharedFields:Ot}=n.saveCalculatedFieldToCardScope({activeFields:Re,storedFields:Y.calculatedFields||[],sharedFields:Be,updatedField:H,editingField:et,previousScope:dt});qe&&oe.updateCardConfig(m.id,{metricColumns:qe}),oe.updateCard(m.id,{calculatedFields:wt}),Ot!==Be&&n.commitSharedCalculatedFields({nextSharedFields:Ot,currentSharedFields:Be,isVisualEditing:y,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w})},onSaveToDashboard:H=>{var ln;if(H.role!=="metric")return;const{card:Y,frame:he,actions:oe}=t.useEditorStore.getState(),Re=s,Be=((ln=Y.config)==null?void 0:ln.metricColumns)||[],qe=he.calculatedFields||[],{nextActiveFields:wt,nextStoredFields:Ot,nextSharedFields:Pt}=n.saveCalculatedFieldToSharedScope({activeFields:Be,storedFields:Y.calculatedFields||[],sharedFields:qe,updatedField:{...H,id:Re.id,aliasTemplate:Re.aliasTemplate,valueAliases:Re.valueAliases,parameters:Re.parameters,customFormat:Re.customFormat},editingField:et,previousScope:dt});n.commitSharedCalculatedFields({nextSharedFields:Pt,currentSharedFields:qe,isVisualEditing:y,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:w}),wt&&oe.updateCardConfig(m.id,{metricColumns:wt}),oe.updateCard(m.id,{calculatedFields:Ot})},cardId:m.id})]})}function Oo({concept:s}){const{title:a,description:r}=Po[s];return e.jsxs(n.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(n.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(n.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-control border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(Bo,{highlight:s})]})]})}const Po={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function Bo({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",l=s==="metrics",u="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-control border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(c=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&u),children:c},c))]})}),e.jsx("tbody",{children:kn.map((c,o)=>e.jsxs("tr",{className:t.cn(o!==kn.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",r&&u),children:c.label}),c.values.map((d,i)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",l&&u),children:d},i))]},c.label))})]})})}const kn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],Vo={groupBy:$t,pivotBy:hs,metrics:Ra,detailColumns:t.Table2,sortBy:Mn};function Et({zone:s,fields:a,label:r,placeholder:l,shouldShow:u,hasPivotColumns:c=!1,activeField:o=null}){const{isOver:d,setNodeRef:i}=n.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),h=t.useEditorStore(w=>w.card),v=t.useEditorStore(w=>w.card.type),f=a.length>0,m=C.useMemo(()=>!o||!d?!0:n.validateFieldForChartType(o,s,v).isValid,[o,d,s,v]),g=(w,A)=>{var S;!((S=h.config)!=null&&S.sortByColumns)||h.config.sortByColumns.findIndex(E=>E.id===w)===-1||x(h.id,w,{direction:A})};if(s==="sortBy"&&u===!1)return null;const y=s!=="sortBy"&&v!=="kpi",b=Vo[s]||n.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r}),e.jsx("div",{ref:i,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":d&&m,"border border-destructive/40 bg-destructive/5":d&&!m,"border border-dashed border-border/50 bg-background":!d&&!f}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(b,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:l}),y&&e.jsx(Oo,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(w=>w.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((w,A)=>{const S=w.direction;return e.jsx(Ro,{field:w,zone:s,index:A,sortDirection:S,onSortDirectionChange:E=>g(w.id,E),hasPivotColumns:c,cardType:v},w.id)})})})})]})}function zo({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:l,detailFields:u,activeField:c}){var _,q,W;const[o,d]=C.useState(!1);t.useEditorStore($=>{var U;return!!((U=$.card.customCardPreferences)!=null&&U.url)});const i=t.useEditorStore($=>$.card),x=t.useEditorStore($=>$.frame),h=n.findCustomVisualConfigCard(x,i),{manifest:v}=n.useCustomVisual(((_=h==null?void 0:h.customCardPreferences)==null?void 0:_.url)||""),f=(q=v==null?void 0:v.visuals)==null?void 0:q.find($=>{var U;return $.name===((U=h==null?void 0:h.customCardPreferences)==null?void 0:U.componentName)}),m=n.resolveMultiInputType(h,f)==="multiple";m&&((W=h==null?void 0:h.customCardPreferences)!=null&&W.url);const g=n.getConfigSlotExpectedType(f==null?void 0:f.slots),y=t.useEditorStore($=>$.actions.updateCardConfig),b=t.useEditorStore($=>$.actions.updateCard),w=t.useEditorStore($=>$.actions.updateFrame),A=t.useDashboardStore($=>$.isVisualEditing),B=t.useDashboardStore($=>$.selectedSheetId),S=t.useDashboardStore($=>$.actions.updateSheetCalculatedFields),{scopedFields:E}=n.useScopedFields(),{userContext:I}=n.useCurrentUserInfo(),T=m&&(h==null?void 0:h.id)===i.id&&g?g:i==null?void 0:i.type,N=T==="detailTable",M=s.length>0||r.length>0||u.length>0,j=!N&&(T!=="kpi"||r.length<=2),O=!N,D=!N&&T!=="kpi",L=T!=="kpi"&&M,R=N,p="Drop sort fields here",F=(I==null?void 0:I.type)==="organization",k=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),P=D&&!k,V=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},z=()=>T==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),M&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{y(i.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[j&&e.jsx(Et,{zone:"groupBy",fields:s,label:V().label,placeholder:V().placeholder,activeField:c}),P&&e.jsx(Et,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:c}),O&&e.jsx(Et,{zone:"metrics",fields:r,label:z().label,placeholder:z().placeholder,hasPivotColumns:a.length>0,activeField:c}),R&&e.jsx(Et,{zone:"detailColumns",fields:u,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&F&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),L&&e.jsx(Et,{zone:"sortBy",fields:l,label:"Sort By",placeholder:p,activeField:c})]}),e.jsx(n.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:E,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{if($.role!=="metric")return;const{nextStoredFields:U}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:i.calculatedFields||[],sharedFields:x.calculatedFields||[],updatedField:$,previousScope:"card"});b(i.id,{calculatedFields:U})},onSaveToDashboard:$=>{if($.role!=="metric")return;const U=x.calculatedFields||[],{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:i.calculatedFields||[],sharedFields:U,updatedField:$,previousScope:"dashboard"});n.commitSharedCalculatedFields({nextSharedFields:se,currentSharedFields:U,isVisualEditing:A,selectedSheetId:B,updateFrame:w,updateSheetCalculatedFields:S})},cardId:i.id})]})}function _o(){var g,y,b;const[s,a]=C.useState(!1),[r,l]=C.useState(!1),u=t.useEditorStore(w=>{var A;return!!((A=w.card.customCardPreferences)!=null&&A.url)}),c=t.useEditorStore(w=>w.card),o=t.useEditorStore(w=>w.frame),d=n.findCustomVisualConfigCard(o,c),{manifest:i}=n.useCustomVisual(((g=d==null?void 0:d.customCardPreferences)==null?void 0:g.url)||""),x=(y=i==null?void 0:i.visuals)==null?void 0:y.find(w=>{var A;return w.name===((A=d==null?void 0:d.customCardPreferences)==null?void 0:A.componentName)}),v=n.resolveMultiInputType(d,x)==="multiple"&&!!((b=d==null?void 0:d.customCardPreferences)!=null&&b.url),f=!u||v,m=u||v;return!f&&!m?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[f&&s&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-border px-4",children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60",children:e.jsx(ea,{mode:"config"})})}),f&&e.jsxs("button",{type:"button",onClick:()=>a(w=>!w),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Chart settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",s&&"rotate-180"),strokeWidth:1.75})]}),m&&r&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Jn,{})}),m&&e.jsxs("button",{type:"button",onClick:()=>l(w=>!w),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",f&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ln,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]})]})}function qo({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:l}=r,u=(l==null?void 0:l.joins)||[];if(u.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(i=>{var f,m,g,y;const x=`${(f=i.source)==null?void 0:f.entityName}.${(m=i.source)==null?void 0:m.name}`,h=`${(g=i.target)==null?void 0:g.entityName}.${(y=i.target)==null?void 0:y.name}`,v=i.operator||"=";return`${x} ${v} ${h}`}).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((i,x)=>({id:x,operator:i.operator,condition:c(i.keys)}));return e.jsx(n.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(_a,{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(n.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:u.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:u.map((d,i)=>{const x=o(d),h=Array.isArray(x);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(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(n.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:h?x.map(v=>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:v.condition}),v.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",v.operator,")"]})]},v.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:x})})})]},d.id||i)})})})]})})]}),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(n.SquarePen,{className:"size-3.5"})})]})})}function $o({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:l,groupByFields:u,pivotByFields:c,metricsFields:o,sortByFields:d,detailFields:i,activeField:x}){var T,N;const[h,v]=C.useState(!1),f=t.useEditorStore(M=>M.card),m=t.useEditorStore(M=>M.editorContext),g=t.useEditorStore(M=>M.actions.updateCardConfig),y=(m==null?void 0:m.type)==="documentSection",{autoJoinMetadata:b}=n.useEditorCardQuery(f),w=((T=f==null?void 0:f.config)==null?void 0:T.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),A=((N=f==null?void 0:f.dataSource)==null?void 0:N.selectedEntities)||[],B=M=>{g(f.id,{...f==null?void 0:f.config,joinPlan:M}),v(!1)},S=()=>{g(f.id,{...f==null?void 0:f.config,joinPlan:void 0}),v(!1)},E=()=>{v(!1)},I=()=>{v(!0)};return r?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!y&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(wr,{selectedChart:s,onChartChange:a})}),l&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:l,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx(qo,{onEditJoins:I})}),e.jsx(zo,{groupByFields:u,pivotByFields:c,metricsFields:o,sortByFields:d,detailFields:i,activeField:x})]}),e.jsx(_o,{}),e.jsx(Pn,{open:h,onOpenChange:v,joinPlan:w,availableDataSources:A,onSave:B,onCancel:E,onRemove:S,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:l&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:l,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function Ko({initialFilters:s,availableFields:a}={}){const[r,l]=C.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:u,isLoading:c}=n.useFilterableFields(),o=a||u||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},i=S=>{const E=I=>{if(I.id===S){const T=o[0]||d,N=t.getDataType(T.dataType)==="date";return{...I,conditions:[...I.conditions,{id:`condition-${Date.now()}`,field:T,operator:N?"between":"=",value:N?[]:""}]}}return{...I,groups:I.groups.map(E)}};l(E(r))},x=S=>{const E=I=>{if(I.id===S){const T=o[0]||d,N=t.getDataType(T.dataType)==="date";return{...I,groups:[...I.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...I,groups:I.groups.map(E)}};l(E(r))},h=(S,E)=>{const I=T=>T.id===S?{...T,conditions:T.conditions.filter(N=>N.id!==E)}:{...T,groups:T.groups.map(I)};l(I(r))},v=(S,E)=>{const I=T=>T.id===S?{...T,groups:T.groups.filter(N=>N.id!==E)}:{...T,groups:T.groups.map(I)};l(I(r))},f=(S,E,I,T)=>{if(I==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=M=>M.id===S?{...M,conditions:M.conditions.map(j=>j.id===E?{...j,[I]:T}:j)}:{...M,groups:M.groups.map(N)};l(N(r))},m=(S,E,I)=>{const T=N=>N.id===S?{...N,conditions:N.conditions.map(M=>M.id===E?{...M,...I}:M)}:{...N,groups:N.groups.map(T)};l(T(r))},g=(S,E)=>{const I=T=>T.id===S?{...T,logicalOperator:E}:{...T,groups:T.groups.map(I)};l(I(r))},y=(S,E)=>{const I=T=>T.id===S?{...T,negate:E}:{...T,groups:T.groups.map(I)};l(I(r))},b=(S,E,I)=>{const T=N=>N.id===S?{...N,conditions:n.arrayMove(N.conditions,E,I)}:{...N,groups:N.groups.map(T)};l(T(r))},w=(S,E,I)=>{const T=N=>N.id===S?{...N,groups:n.arrayMove(N.groups,E,I)}:{...N,groups:N.groups.map(T)};l(T(r))},A=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const E=T=>{let N="";typeof T.field=="object"?N=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:N=String(T.field);const M=T.operator;let j=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(T.field.dataType==="date"||T.field.dataType==="datetime"||T.field.dataType==="timestamp")if(T.operator==="between"&&Array.isArray(j)&&j.length===2){const O=j[0]?`'${j[0]}'`:"NULL",D=j[1]?`'${j[1]}'`:"NULL";return`${N} BETWEEN ${O} AND ${D}`}else if((T.operator==="in"||T.operator==="not in")&&Array.isArray(j)){const O=j.map(D=>D?`'${D}'`:"NULL").join(", ");return`${N} ${M} (${O})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(T.operator)){let O=[];Array.isArray(j)?O=j.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof j=="string"?O=j.split(",").map(D=>{const L=D.trim();return T.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(O=[String(j)]),j=`(${O.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${N} LIKE '%${j.replace(/'/g,"")}'`:`${N} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${N} LIKE '${j.replace(/'/g,"")}%'`:`${N} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${N} LIKE '%${j.replace(/'/g,"")}'`:`${N} LIKE '%${String(j)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${M} ${j}`}},I=T=>{const N=T.conditions.map(E),M=T.groups.map(L=>I(L)),j=[...N,...M].filter(Boolean);if(j.length===0)return"";const O=j.join(` ${T.logicalOperator} `),D=j.length>1?`(${O})`:O;return T.negate?`NOT ${D}`:D};return I(S)},B=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:l,availableFields:o,isLoading:c,addCondition:i,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:f,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:y,reorderConditions:b,reorderGroups:w,generateSQLPreview:A,hasAnyFilters:B}}function Go({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Uo=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ho({value:s,onValueChange:a,availableFields:r,placeholder:l="Select field",className:u="w-64"}){const[c,o]=C.useState(!1),d=C.useMemo(()=>{const i={};return r.forEach(x=>{const h=Uo(x);i[h]||(i[h]={}),i[h][x.entityId]||(i[h][x.entityId]=[]),i[h][x.entityId].push(x)}),i},[r]);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",u),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Go,{children:[s.entityName,".",s.name]})}):l,e.jsx(n.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(n.CommandEmpty,{children:"No fields found."}),e.jsx(n.CommandList,{className:"max-h-80",children:Object.entries(d).map(([i,x])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),i]}),children:Object.entries(x).map(([h,v])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[n.getEntityIcon(v[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:v[0].entityName})]}),v.map((f,m)=>e.jsxs(n.CommandItem,{value:f.id,onSelect:()=>{a(f),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)===f.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:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+m))]},`${i}-${h}`))},i))})]})})]})}function ys(s){var y;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:l}=n.useSemaphorContext(),u=t.useEditorStore(b=>b.card.config),c=u==null?void 0:u.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[o],metricColumns:[d],sortByColumns:[i]},h=((y=a.dataSource)==null?void 0:y.connectionId)||a.connectionId,{data:v,isPending:f,error:m}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:h,cardConfig:x,cardDataSource:a.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((v==null?void 0:v.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:f,error:m}}function Qo({field:s,selected:a,onChange:r,placeholder:l="Select items...",className:u}){const[c,o]=zt.useState(!1),{filterValues:d}=ys(s),i=h=>{r(a.filter(v=>v!==h))},x=h=>{a.includes(h)?r(a.filter(v=>v!==h)):r([...a,h])};return e.jsx("div",{className:t.cn("w-full",u),children:e.jsxs(t.Popover,{open: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:a.length>0?a.map(h=>{const v=d.find(f=>f.value===h);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[v==null?void 0:v.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&i(h)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),i(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:l})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No results found."}),e.jsx(n.CommandGroup,{children:d.map((h,v)=>e.jsxs(n.CommandItem,{onSelect:()=>x(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+v))})]})]})})]})})}function Wo({field:s,value:a,onChange:r,placeholder:l="Select value...",className:u}){const{filterValues:c,isPending:o,error:d}=ys(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:u||"flex-1",children:e.jsx(t.SelectValue,{placeholder:l,children:a})}),e.jsx(t.SelectContent,{children:c.map((i,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:i.value,children:i.label},i.value+x))})]})}function Jo({value:s,operator:a,onChange:r,className:l}){var m,g,y;const{tokenProps:u}=n.useSemaphorContext(),c=((g=(m=u==null?void 0:u.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((y=u==null?void 0:u.params)==null?void 0:y.timezone),o=c||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",i=C.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,w=s[1]?new Date(s[1]):void 0;if(b&&w)return{from:b,to:w}}},[s,d]),x=C.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const w=new Date(b);if(!isNaN(w.getTime()))return w},[s,d]),h=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,o):t.startOfDayInTimezone(b,o),v=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},f=b=>{if(!b){r("");return}const w=h(b);r(w.toISOString())};return e.jsx(n.DateRangePicker,{value:d?i:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:x,onChange:v,onSingleChange:f,timezone:c,showRelativeTab:d,className:l,placeholder:"Select date..."})}const Yo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Xo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Zo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ei=["=","!=","isNull","isNotNull"],ti=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],si={"=":"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 Dn(s){return si[s]||t.titleCase(s)}function ni(s){switch(s){case"string":return Xo;case"number":return Zo;case"boolean":return ei;case"date":return ti;default:return Yo}}function sa({condition:s,index:a,groupId:r,groupLogicalOperator:l,onUpdateCondition:u,onRemoveCondition:c,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:i}){const{attributes:x,listeners:h,setNodeRef:v,transform:f,transition:m,isDragging:g}=n.useSortable({id:s.id}),{isPending:y,error:b}=ys(s.field),w={transform:n.CSS.Transform.toString(f),transition:m};return e.jsxs("div",{ref:v,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",{...x,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:l,onValueChange:A=>o(r,A),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Ho,{value:s.field,onValueChange:A=>{const B=A,S=t.getDataType(B.dataType)==="date";i(r,s.id,{field:B,value:"",operator:S?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:A=>{A==="in"||A==="not in"?i(r,s.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?i(r,s.id,{operator:A,value:null}):A==="between"||A==="not between"?i(r,s.id,{operator:A,value:[]}):i(r,s.id,{operator:A,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Dn(s.operator):""})}),e.jsx(t.SelectContent,{children:ni(t.getDataType(s.field.dataType)).map(A=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:A,children:Dn(A)},A))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?y?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Qo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(A=>typeof A=="string")?s.value:[],onChange:A=>i(r,s.id,{value:A}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:A=>i(r,s.id,{value:A.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Wo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:A=>i(r,s.id,{value:A}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:A=>i(r,s.id,{value:A==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Jo,{value:s.value,operator:s.operator,onChange:A=>i(r,s.id,{value:A}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:A=>u(r,s.id,"value",A.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>c(r,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function ai({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:l,onUpdateGroupNegate:u,onRemoveGroup:c,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:i,onReorderConditions:x,onReorderGroups:h,onAddCondition:v,onAddGroup:f,availableFields:m,renderFilterGroup:g,updateConditionFields:y}){const{attributes:b,listeners:w,setNodeRef:A,transform:B,transition:S,isDragging:E}=n.useSortable({id:s.id}),I={transform:n.CSS.Transform.toString(B),transition:S},T=M=>{const{active:j,over:O}=M;if(O&&j.id!==O.id){const D=s.conditions.findIndex(R=>R.id===j.id),L=s.conditions.findIndex(R=>R.id===O.id);D!==-1&&L!==-1&&x(s.id,D,L)}},N=M=>{const{active:j,over:O}=M;if(O&&j.id!==O.id&&r){const D=s.groups.findIndex(R=>R.id===j.id),L=s.groups.findIndex(R=>R.id===O.id);D!==-1&&L!==-1&&h(r,D,L)}};return e.jsxs("div",{ref:A,style:I,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...w,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>u(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:M=>l(s.id,M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>r&&c(r,s.id),children:e.jsx(n.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:T,children:e.jsx(n.SortableContext,{items:s.conditions.map(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((M,j)=>e.jsx(sa,{condition:M,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:m,updateConditionFields:y},M.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:N,children:e.jsx(n.SortableContext,{items:s.groups.map(M=>M.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(M=>g(M,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>v(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ri({filters:s,availableFields:a,onSave:r,onClearAll:l,onCancel:u}){const{currentFilters:c,availableFields:o,isLoading:d,addCondition:i,addGroup:x,removeCondition:h,removeGroup:v,updateCondition:f,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:y,reorderConditions:b,reorderGroups:w,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:S}=Ko({initialFilters:s,availableFields:a}),E=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[I,T]=C.useState(!1),N=(O,D,L)=>{const R=p=>p.id===O?{...p,conditions:p.conditions.map(F=>F.id===D?{...F,field:L,dataType:L.dataType}:F)}:{...p,groups:p.groups.map(R)};S(R(c))},M=(O,D=0,L)=>D===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:p,over:F}=R;if(F&&p.id!==F.id){const k=O.conditions.findIndex(V=>V.id===p.id),P=O.conditions.findIndex(V=>V.id===F.id);k!==-1&&P!==-1&&b(O.id,k,P)}},children:e.jsx(n.SortableContext,{items:O.conditions.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:O.conditions.map((R,p)=>e.jsx(sa,{condition:R,index:p,groupId:O.id,groupLogicalOperator:O.logicalOperator,onUpdateCondition:f,onUpdateField:N,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:m},R.id))})}),e.jsx(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:p,over:F}=R;if(F&&p.id!==F.id){const k=O.groups.findIndex(V=>V.id===p.id),P=O.groups.findIndex(V=>V.id===F.id);k!==-1&&P!==-1&&w(O.id,k,P)}},children:e.jsx(n.SortableContext,{items:O.groups.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:O.groups.map(R=>M(R,D+1,O.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:()=>i(O.id),children:[e.jsx(n.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:()=>x(O.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},O.id):e.jsx(ai,{group:O,depth:D,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:y,onRemoveGroup:v,onUpdateCondition:f,onUpdateField:N,onRemoveCondition:h,onReorderConditions:b,onReorderGroups:w,onAddCondition:i,onAddGroup:x,availableFields:o,renderFilterGroup:M,updateConditionFields:m},O.id),j=n.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(n.Card,{children:e.jsx(n.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):M(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.Switch,{size:"sm",id:"advanced-mode",checked:I,onCheckedChange:O=>T(O)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:A(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:u,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:l,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(B?c:null),children:"Apply Filters"})]})]})}function li({cardId:s,filters:a,onFiltersChange:r,onClearFilters:l,availableFields:u,isOpen:c,onOpenChange:o}){const d=x=>{r(s,x),o(!1)},i=()=>{l(s),o(!1)};return e.jsxs(n.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(n.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Card Filters"}),e.jsx(n.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ri,{filters:a,availableFields:u,onSave:d,onCancel:()=>o(!1),onClearAll:i})]})]})}function oi({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:l}){var A,B;const[u,c]=C.useState(null),o=t.useEditorStore(S=>S.card),d=t.useEditorStore(S=>S.actions.updateCardConfig),i=t.useEditorStore(S=>S.actions.setCardPreferences),x=(A=o==null?void 0:o.config)==null?void 0:A.joinPlan,h=C.useCallback(S=>S.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),v=(B=o==null?void 0:o.dataSource)==null?void 0:B.semanticDomainId,{data:f}=n.useJoinabilityMap(v),m=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],g=C.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(E=>E.id===S)?"source":r("groupBy").find(E=>E.id===S)?"groupBy":r("metrics").find(E=>E.id===S)?"metrics":r("pivotBy").find(E=>E.id===S)?"pivotBy":r("sortBy").find(E=>E.id===S)?"sortBy":r("detailColumns").find(E=>E.id===S)?"detailColumns":null,[a,r]),y=C.useCallback(S=>{c(S.active.id)},[]),b=C.useCallback(S=>{var O;const{active:E,over:I}=S;if(!I||!s){c(null);return}const T=E.id,N=I.id,M=g(T),j=g(N)||N;if(j==="sortBy"){if(M==="source"){const D=a.find(R=>R.id===T);if(!D){c(null);return}if(!(r("groupBy").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName)||r("metrics").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName)||r("detailColumns").some(R=>R.name===D.name&&R.qualifiedEntityName===D.qualifiedEntityName))){c(null);return}}else if(M==="pivotBy"){c(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){c(null);return}}if(M==="source"&&j==="sortBy"){const D=[...a].find(F=>F.id===T);if(!D){c(null);return}const L=r("sortBy");if(n.fieldAlreadyExists(D,L)){c(null);return}const R=n.validateFieldForChartType(D,"sortBy",o.type);if(!R.isValid){n.ue.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3}),c(null);return}const p=n.getNewField(D,"sortBy",L);c(null),l("sortBy",[...L,p]);return}if(M==="source"&&j!=="source"&&j!=="sortBy"){const D=[...a].find(V=>V.id===T);if(!D){c(null);return}const L=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],R=L.filter(V=>!h(V));if(R.length>0){const V=R[0].qualifiedEntityName;if(!V){c(null);return}if(V!==D.qualifiedEntityName&&!h(D)&&D.qualifiedEntityName)if(v&&(f!=null&&f.joinabilityMap)){if(n.calculateFieldState(D,{joinabilityMap:f.joinabilityMap,selectedFields:L,baseEntityName:(O=x==null?void 0:x.baseEntity)==null?void 0:O.name}).state==="unreachable"){n.showJoinRequiredNotification(),c(null);return}}else{if(!x){n.showJoinRequiredNotification(),c(null);return}if(!n.areEntitiesJoined(V,D.qualifiedEntityName,x)){n.showJoinRequiredNotification(),c(null);return}}}const p=r(j);if(n.fieldAlreadyExists(D,p)){c(null);return}const F=n.validateFieldForChartType(D,j,o.type);if(!F.isValid){n.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const k=n.getNewField(D,j,p),P=[...p,k];if(c(null),l(j,P),j==="metrics"&&s){const V=n.seedSemanticMetricFormatDefaults(o,k,o.preferences);V&&i(V),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(M&&j&&M!=="source"&&j!=="source"&&M!==j){const D=r(M),L=r(j),R=D.find(V=>V.id===T);if(!R){c(null);return}const p=n.validateFieldForChartType(R,j,o.type);if(!p.isValid){n.ue.error("Invalid Field Type",{description:p.reason,position:"top-center",duration:3e3}),c(null);return}const F=n.getNewField(R,j,L);if(c(null),j==="sortBy"){n.fieldAlreadyExists(R,L)||l(j,[...L,F]);return}const k=D.filter(V=>V.id!==T),P=[...L,F];if(l(M,k),l(j,P),j==="metrics"&&s){const V=n.seedSemanticMetricFormatDefaults(o,F,o.preferences);V&&i(V),n.cleanupKpiMetricComparisonMode(o.type,o.config,d,s,P)}return}if(M&&j&&M===j&&M!=="source"){const D=r(M),L=D.findIndex(p=>p.id===T),R=D.findIndex(p=>p.id===N);if(L!==R){const p=n.arrayMove(D,L,R);l(M,p)}}c(null)},[s,a,r,l,g,x,v,f,h,o,d,i]),w=u?m.find(S=>S.id===u):null;return{activeId:u,activeField:w,handleDragStart:y,handleDragEnd:b}}function ii({activeView:s,onViewChange:a,splitViewEnabled:r}){const l=t.useEditorStore(i=>i.card),{config:u}=C.useContext(n.SemaphorContext).tokenProps,c=(u==null?void 0:u.showInfoTab)!==!1,o=()=>r?!1:t.getVisualizationMode(l)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(l.type),d=[{id:"chart",label:"Chart"}];return o()&&d.push({id:"table",label:"Results"}),l.type!=="kpi"&&c&&d.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:i=>a(i),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:d.map(i=>{const x=i.icon;return e.jsxs(t.TabsTrigger,{value:i.id,className:"gap-1.5 px-0 text-[13px]",children:[x&&e.jsx(x,{className:"h-3 w-3",strokeWidth:1.75}),i.label]},i.id)})})})}const ci=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function di(){var i,x;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[r,l]=C.useState(!1),[u,c]=C.useState(""),o=h=>{if(h==="custom"){l(!0);return}l(!1),a(s.id,parseInt(h))},d=h=>{const v=h.target.value;c(v),v&&!isNaN(parseInt(v))&&a(s.id,parseInt(v))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:u,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(i=s.config)==null?void 0:i.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(n.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:ci.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function ui({card:s,queryData:a,isLoading:r,isFetching:l,pagination:u,onPaginationChange:c,onSortChange:o,sortState:d,splitViewEnabled:i,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:h}){const v=C.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),f=t.getVisualizationMode(s)==="dynamic",m=e.jsx(it,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Hn,{fallbackPreview:e.jsx(it,{}),records:v,title:s.title,isInspectorOpen:x,onInspectorOpenChange:h})});return f?i?e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(r||l)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:v,paginationMetadata:u,onPaginationChange:c,isLoading:r||l,onSortChange:o,sortState:d})]})})]}):m:!i||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(it,{}):e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(it,{})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(r||l)&&(a==null?void 0:a.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:v,paginationMetadata:u,onPaginationChange:c,isLoading:r||l,onSortChange:o,sortState:d})]})})]})}function mi(s,a){const[r,l]=C.useState(()=>{const u=localStorage.getItem(s);return u?JSON.parse(u):a});return C.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,l]}const xi="semaphor-split-view-enabled";function hi(){return mi(xi,!0)}function pi({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:l,columns:u}){var Z,je,Ie;const c=t.useEditorStore(ne=>ne.card),o=t.useEditorStore(ne=>ne.editorContext),d=t.useEditorStore(ne=>ne.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),i=t.useEditorStore(ne=>ne.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ne=>ne.filterValues),h=t.useDashboardStore(ne=>ne.selectedSheetId),{updateCardConfig:v,setCard:f,updateCardInFrame:m,setShowAIDialog:g}=t.useEditorActions(),y=t.useEditorStore(ne=>ne.showAIDialog),b=t.useEditorStore(ne=>ne.isDevMode),w=t.useDashboardStore(ne=>ne.isVisualEditing),[A,B]=C.useState(!1),[S,E]=C.useState(!1),[I,T]=C.useState(!1),[N,M]=C.useState(null),{config:j}=C.useContext(n.SemaphorContext).tokenProps,O=(j==null?void 0:j.showInfoTab)!==!1,D=(j==null?void 0:j.showQueryDebugTools)!==!1,[L,R]=hi();t.useEditorStore(ne=>{var Ae;return!!((Ae=ne.card.customCardPreferences)!=null&&Ae.url)});const F=t.getVisualizationMode(c)==="dynamic",k=(o==null?void 0:o.type)==="documentSection",{data:P,errorMessage:V,isLoading:z,isFetching:_,errorSql:q,pagination:W,refetch:$,comparisonMetadata:U,queryRequestPayload:se,resolvedPrimaryDateField:ie}=n.useEditorCardQuery(l),le=C.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[de,me]=C.useState(!1);C.useEffect(()=>{_||me(!1)},[_]);const ue=()=>{const ne=!L;ne&&s==="table"&&a("chart"),R(ne)},Ne=(ne,Ae)=>{const Le={...l,paginationConfig:{page:ne+1,pageSize:Ae}};f(Le),m(Le)},we=ne=>{if(!c.config)return;const Ae=n.sortStateToSortByColumns(ne,c.config.metricColumns,c.config.groupByColumns,c.config.detailColumns);v(c.id,{...c.config,sortByColumns:Ae})},Te=C.useMemo(()=>{var ne;return n.sortByColumnsToSortState((ne=c.config)==null?void 0:ne.sortByColumns)},[(Z=c.config)==null?void 0:Z.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":y&&w}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&y&&!k&&!F&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Sr,{variant:b?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(ii,{activeView:s,onViewChange:a,splitViewEnabled:L}),e.jsx(di,{})]}),U&&c.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),y&&e.jsx(Me.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:l.id,cardFilters:(je=l.config)==null?void 0:je.filters,cardFilterCount:n.getFilterCount(((Ie=l.config)==null?void 0:Ie.filters)||null),onFiltersClick:r,inlineFilters:l.inlineFilters,inlineFilterValues:d,sheetId:h||"",removeInlineFilterValue:ne=>i(l.id,ne),resolvedPrimaryDateField:ie}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:z||_,onClick:()=>{me(!0),$()},children:e.jsx(n.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":de})})}),s==="chart"&&!F&&e.jsx(Un,{showInlineFilters:!1,showDisplayOptions:!1}),s==="chart"&&e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"More Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:ue,children:[L?e.jsx(wa,{className:"mr-2 h-4 w-4"}):e.jsx(Ba,{className:"mr-2 h-4 w-4"}),L?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(gs,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Qn,{onCustomize:()=>T(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col",children:e.jsx(ui,{card:l,queryData:P,isLoading:z,isFetching:_,pagination:W,onPaginationChange:Ne,onSortChange:we,sortState:Te,splitViewEnabled:L,isDynamicInspectorOpen:I,onDynamicInspectorOpenChange:T})}),s==="table"&&(P==null?void 0:P.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(z||_)&&(P==null?void 0:P.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(n.TableVisual,{card:l,data:le,comparisonMetadata:U,paginationMetadata:W,onPaginationChange:Ne,isLoading:z||_,onSortChange:we,sortState:Te})]}),s==="info"&&O&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-4",children:V?e.jsx(ps,{error:V,errorSql:q,onSendFeedback:()=>{const ne=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:c.config,dataSource:l.dataSource,dashboardFilters:x,errorMessage:V,errorSql:q,generatedSql:P==null?void 0:P.sql});M(ne),E(!0)},onOpenInEditor:()=>{g(!0),setTimeout(()=>{const ne=t.useEditorStore.getState().actions;ne.setIsDevMode(!0),ne.setCardSql(q||""),setTimeout(()=>{ne.setRunSql(!0)},100)},100)}}):(P==null?void 0:P.sql)&&e.jsx(Wn,{sql:P.sql,showCardDetails:!0,debugPayloads:D?{queryRequest:se,queryResponse:P,columns:u,dashboardFilters:x}:void 0})})})]}),N&&e.jsx(n.FeedbackDialog,{open:S,onOpenChange:E,feedbackData:N})]})})}function fi({activeField:s}){const[a,r]=C.useState(!0);if(C.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const l=!!n.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(n.TypeGlyph,{dataType:s.dataType,calculated:l}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const gi=()=>{const s=console.error;console.error=(...l)=>{l.length>0&&typeof l[0]=="string"&&l[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,l)};const a=l=>{if(l.message&&(l.message.includes("ResizeObserver loop completed with undelivered notifications")||l.message.includes("ResizeObserver loop limit exceeded")))return l.preventDefault(),l.stopPropagation(),!1},r=l=>{var u;if((u=l.reason)!=null&&u.message&&(l.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||l.reason.message.includes("ResizeObserver loop limit exceeded")))return l.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",r,!0)}};function bi({column:s,isSelected:a,onSelect:r,availableFields:l,width:u,onWidthChange:c}){var V,z,_;const o=t.useEditorStore(q=>q.card),{updateCardConfig:d,removeGroupByColumn:i,removeMetricColumn:x,updateFilters:h}=t.useEditorActions(),[v,f]=C.useState(!1),[m,g]=C.useState(!1),y=C.useRef(null),b=C.useCallback(q=>{q.preventDefault(),q.stopPropagation(),g(!0),y.current={startX:q.clientX,startWidth:u||150};const W=U=>{if(!y.current)return;const se=U.clientX-y.current.startX,ie=Math.max(80,y.current.startWidth+se);c==null||c(s.id,ie)},$=()=>{g(!1),y.current=null,document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",$)};document.addEventListener("mousemove",W),document.addEventListener("mouseup",$)},[u,s.id,c]),w=(V=o==null?void 0:o.config)==null?void 0:V.filters,A=(z=w==null?void 0:w.conditions)==null?void 0:z.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),B=q=>{q?h(o.id,q):d(o.id,{filters:void 0})},{attributes:S,listeners:E,setNodeRef:I,transform:T,transition:N,isDragging:M}=n.useSortable({id:s.id}),j={transform:n.CSS.Transform.toString(T),transition:N},O=t.getDataType(s.dataType),D=ji(O),L=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.sortByColumns)||[],W=q.findIndex(U=>U.name===s.name);if(W!==-1){const U=[...q];U[W]={...U[W],direction:"asc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.sortByColumns)||[],W=q.findIndex(U=>U.name===s.name);if(W!==-1){const U=[...q];U[W]={...U[W],direction:"desc"},d(o.id,{sortByColumns:U})}else d(o.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},p=()=>{var $;const q=(($=o==null?void 0:o.config)==null?void 0:$.groupByColumns)||[];if(!q.some(U=>U.name===s.name)){const U={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...q,U]})}},F=q=>{var U;const W=((U=o==null?void 0:o.config)==null?void 0:U.metricColumns)||[];if(!W.some(se=>se.name===s.name&&se.aggregate===q)){const se={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q};d(o.id,{metricColumns:[...W,se]})}},k=()=>{s.role==="groupby"?i(o.id,s.id):s.role==="metric"&&x(o.id,s.id)},P={...j,width:u?`${u}px`:void 0,minWidth:u?`${u}px`:"120px"};return e.jsxs("th",{ref:I,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...E,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:r,className:t.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(D,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),A&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>f(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:L,children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:R,children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(n.DropdownMenuSubContent,{children:[e.jsx(n.DropdownMenuItem,{onClick:()=>F("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>F("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:p,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(hs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(n.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(n.DropdownMenuItem,{onClick:k,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(ta,{open:v,onOpenChange:f,availableFields:l.length>0?l:[s],existingFilters:w,editingCondition:A?(_=w==null?void 0:w.conditions)==null?void 0:_.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function ji(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function vi({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:l=[],filterableFields:u=l}){var M,j,O,D;const c=t.useEditorStore(L=>L.card),{updateCardConfig:o}=t.useEditorActions(),[d,i]=C.useState(null),[x,h]=C.useState({}),[v,f]=C.useState(!1),m=C.useMemo(()=>{var p,F;const L=((p=c==null?void 0:c.config)==null?void 0:p.groupByColumns)||[],R=((F=c==null?void 0:c.config)==null?void 0:F.metricColumns)||[];return[...L,...R]},[(M=c==null?void 0:c.config)==null?void 0:M.groupByColumns,(j=c==null?void 0:c.config)==null?void 0:j.metricColumns]),g=C.useMemo(()=>{const L=new Set(m.map(R=>`${R.qualifiedEntityName}.${R.name}`));return l.filter(R=>!L.has(`${R.qualifiedEntityName}.${R.name}`))},[l,m]),{data:y,isLoading:b}=n.useEditorCardQuery(c),w=(y==null?void 0:y.records)||[],A=C.useCallback((L,R)=>{h(p=>({...p,[L]:R}))},[]),B=C.useCallback(L=>{var k,P;const R=t.getDataType(L.dataType),p=((k=c==null?void 0:c.config)==null?void 0:k.groupByColumns)||[],F=((P=c==null?void 0:c.config)==null?void 0:P.metricColumns)||[];if(R==="number"){const V={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(c.id,{metricColumns:[...F,V]})}else{const V={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};o(c.id,{groupByColumns:[...p,V]})}f(!1)},[(O=c==null?void 0:c.config)==null?void 0:O.groupByColumns,(D=c==null?void 0:c.config)==null?void 0:D.metricColumns,c.id,o]),S=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),E=L=>{i(L.active.id)},I=L=>{const{active:R,over:p}=L;if(i(null),!p||R.id===p.id)return;const F=m.findIndex(P=>P.id===R.id),k=m.findIndex(P=>P.id===p.id);if(F!==-1&&k!==-1){const P=n.arrayMove(m,F,k),V=P.filter(_=>_.role==="groupby"),z=P.filter(_=>_.role==="metric");o(c.id,{groupByColumns:V,metricColumns:z})}},T=d?m.find(L=>L.id===d):null,N=L=>{let R="";for(;L>=0;)R=String.fromCharCode(L%26+65)+R,L=Math.floor(L/26)-1;return R};return r?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"})}):m.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragStart:E,onDragEnd:I,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(n.SortableContext,{items:m.map(L=>L.id),strategy:n.horizontalListSortingStrategy,children:m.map((L,R)=>e.jsx("th",{style:{width:x[L.id]?`${x[L.id]}px`:void 0,minWidth:x[L.id]?`${x[L.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:N(R)},`letter-${L.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(n.SortableContext,{items:m.map(L=>L.id),strategy:n.horizontalListSortingStrategy,children:m.map(L=>e.jsx(bi,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>a(L),availableFields:u,width:x[L.id],onWidthChange:A},L.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:v,onOpenChange:f,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(n.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns available."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:g.map(L=>{const R=t.getDataType(L.dataType),p=R==="number"?n.Hash:R==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:L.label||L.name,onSelect:()=>B(L),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:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.entityName})]})]},L.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):w.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):w.slice(0,100).map((L,R)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",R%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:R+1}),m.map(p=>{const F=L[p.name]??L[p.label??""];return e.jsx("td",{style:{width:x[p.id]?`${x[p.id]}px`:void 0,minWidth:x[p.id]?`${x[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:yi(F,p)})},`${R}-${p.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(n.DragOverlay,{children:T&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:T.label||T.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(w.length,100)," of ",w.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function yi(s,a){if(s==null)return"—";if(typeof s=="number")return a.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Ni({entityGroups:s,isLoading:a=!1}){var B,S;const r=t.useEditorStore(E=>E.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:c}=t.useEditorActions(),[o,d]=C.useState(!0),[i,x]=C.useState(""),[h,v]=C.useState(new Set),f=((B=r==null?void 0:r.config)==null?void 0:B.groupByColumns)||[],m=((S=r==null?void 0:r.config)==null?void 0:S.metricColumns)||[],g=E=>{const I=new Set(h);I.has(E)?I.delete(E):I.add(E),v(I)},y=E=>f.some(I=>I.name===E.name&&I.qualifiedEntityName===E.qualifiedEntityName)||m.some(I=>I.name===E.name&&I.qualifiedEntityName===E.qualifiedEntityName),b=(E,I)=>{if(I)if(t.getDataType(E.dataType)==="number"){const N={...E,id:`metric-${E.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};l(r.id,{metricColumns:[...m,N]})}else{const N={...E,id:`groupby-${E.id}-${Date.now()}`,role:"groupby"};l(r.id,{groupByColumns:[...f,N]})}else{const T=f.findIndex(M=>M.name===E.name&&M.qualifiedEntityName===E.qualifiedEntityName),N=m.findIndex(M=>M.name===E.name&&M.qualifiedEntityName===E.qualifiedEntityName);T!==-1&&u(r.id,f[T].id),N!==-1&&c(r.id,m[N].id)}},w=E=>{if(!i)return E;const I=i.toLowerCase();return E.filter(T=>T.name.toLowerCase().includes(I)||T.label&&T.label.toLowerCase().includes(I))},A=E=>{switch(t.getDataType(E)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(Aa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(n.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:i,onChange:E=>x(E.target.value),className:"h-8 pl-8 text-sm"})]})}),(f.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[f.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx($t,{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:f.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:f.map(E=>{const I=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>u(r.id,E.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},E.id)})})})]}),m.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:m.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(E=>{const I=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(I,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:E.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(r.id,E.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},E.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(E=>{const I=w(E.columns);if(I.length===0)return null;const T=h.has(E.entityId)||i.length>0;return e.jsxs(n.Collapsible,{open:T,onOpenChange:()=>g(E.entityId),children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(n.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",T&&"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:E.label||E.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:I.map(N=>{const M=A(N.dataType),j=y(N);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",j&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:j,onCheckedChange:O=>b(N,O),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:N.label||N.name})]},N.id)})})})]},E.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(Ma,{className:"h-4 w-4"})})})}const Ci=[{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 Si({value:s,onChange:a,onSubmit:r,onCancel:l,selectedColumn:u,availableColumns:c}){const[o,d]=C.useState(!1),[i,x]=C.useState("column"),h=C.useRef(null);C.useEffect(()=>{const g=y=>{y.key==="Escape"&&s?l():y.key==="Enter"&&s&&!o&&r(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,l,r,o]);const v=g=>{const y=`[${g.label||g.name}]`,b=h.current;if(b){const w=b.selectionStart||0,A=b.selectionEnd||0,B=s.slice(0,w)+y+s.slice(A);a(B),setTimeout(()=>{b.setSelectionRange(w+y.length,w+y.length),b.focus()},0)}else a(s+y);d(!1)},f=g=>{const y=h.current;if(y){const b=y.selectionStart||0,w=y.selectionEnd||0,A=s.slice(0,b)+g.syntax+s.slice(w);a(A),setTimeout(()=>{y.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),y.focus()},0)}else a(s+g.syntax);d(!1)},m=g=>{switch(t.getDataType(g)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:u?e.jsx("span",{className:"truncate",children:u.label||u.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&i==="function",onOpenChange:g=>{d(g),g&&x("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Pa,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search functions..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No functions found."}),e.jsx(n.CommandGroup,{heading:"Functions",children:Ci.map(g=>e.jsx(n.CommandItem,{value:g.name,onSelect:()=>f(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&&i==="column",onOpenChange:g=>{d(g),g&&x("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns found."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:c.map(g=>{const y=m(g.dataType);return e.jsxs(n.CommandItem,{value:g.label||g.name,onSelect:()=>v(g),children:[e.jsx(y,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:h,value:s,onChange:g=>a(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:l,title:"Cancel (Esc)",children:e.jsx(t.X,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>r(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function wi({className:s}){var m,g,y,b;const a=t.useEditorStore(w=>w.card),[r,l]=C.useState(null),[u,c]=C.useState(""),{columns:o=[],columnGroups:d=[],isLoading:i}=n.useColumns(),{valuePickFilterableFields:x=[]}=n.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(y=a==null?void 0:a.config)!=null&&y.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const h=w=>{l(w),c(w?`[${w.label||w.name}]`:"")},v=w=>{console.log("Formula submitted:",w),c(""),l(null)},f=()=>{c(""),l(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Si,{value:u,onChange:c,onSubmit:v,onCancel:f,selectedColumn:r,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(vi,{selectedColumn:r,onColumnSelect:h,isLoading:i,sourceFields:o,filterableFields:x})}),e.jsx(Ni,{entityGroups:d,isLoading:i})]})]})}function Ti(){var V,z;const[s,a]=C.useState("chart"),[r,l]=C.useState(!1),[u,c]=C.useState(!0),[o,d]=C.useState(!0),i=t.useEditorStore(_=>_.showAIDialog),x=t.useDashboardStore(_=>_.isVisualEditing),{setCardType:h}=t.useEditorActions(),v=t.useEditorStore(_=>_.card.type);C.useEffect(()=>gi(),[]);const f=_=>{h(_)},m=t.useEditorStore(_=>_.frame),g=t.useEditorStore(_=>_.card);t.useEditorStore(_=>_.activeTabCardId),t.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:y,removeCard:b,updateCard:w,setActiveCard:A,updateFilters:B}=t.useEditorActions(),{columnFields:S=[],scopedFields:E=[],filterableFields:I=[]}=n.useFilterableFields(),T=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),N=g,{getFieldsForContainer:M,setFieldsForContainer:j}=n.useFieldManagement(N),{activeField:O,handleDragStart:D,handleDragEnd:L}=oi({activeCardId:m.activeCardId,sourceFields:E,getFieldsForContainer:M,setFieldsForContainer:j}),R=(_,q)=>{q&&B(_,q)},p=_=>{var q;w(_,{config:{...(q=m.cards.find(W=>W.id===_))==null?void 0:q.config,filters:void 0}})},F=I,k=_=>{if(!_)return 0;let q=_.conditions.length;return _.groups.forEach(W=>{q+=k(W)}),q},P=k(((V=N==null?void 0:N.config)==null?void 0:V.filters)||null);return e.jsxs(n.DndContext,{sensors:T,collisionDetection:n.closestCenter,onDragStart:D,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Bn,{isVisible:u,onToggleVisibility:()=>c(!u)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:v==="tableBuilder"?e.jsx(wi,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!i&&e.jsx($o,{selectedChart:v,onChartChange:f,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:O,isVisible:o,onToggleVisibility:()=>d(!o)}),e.jsx(pi,{selectedChart:v,activeView:s,onViewChange:a,onFiltersClick:()=>l(!0),filterCount:P,activeCard:N,columns:S,getFieldsForContainer:M,cards:m.cards,activeCardId:m.activeCardId,addCard:y,setActiveCard:A})]})}),!u&&x&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(n.Database,{className:"h-4 w-4"})})})]}),N&&e.jsx(li,{cardId:N.id,filters:((z=N.config)==null?void 0:z.filters)||null,onFiltersChange:R,onClearFilters:p,availableFields:F,isOpen:r,onOpenChange:l}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(fi,{activeField:O||null})})]})}function Ei({authToken:s,onSave:a,onClose:r}){const l=C.useRef(null),u=t.useEditorStore(T=>T.showAIDialog),c=t.useEditorStore(T=>T.isDevMode),o=n.useAssistantLayoutStore(T=>T.setFullscreen),d=n.useAssistantLayoutStore(T=>T.setPanelOpen),i=n.useAssistantLayoutStore(T=>T.setContainer),x=n.useAssistantPanel("editor"),h=n.useFullscreenAssistant(),v=n.useAssistantContainer("editor"),f=h==="editor",m=n.useDashboardAppearance(),g=C.useCallback(T=>{i("editor",T)},[i]),{setAuthToken:y}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:w,setOnClose:A}=t.useEditorActions(),{setActiveAssistantType:B}=t.useAIActions();C.useEffect(()=>{a&&w(a),r&&A(r)},[a,w,r,A]),C.useEffect(()=>{s&&s.accessToken&&y(s)},[s,y]),C.useEffect(()=>{var T,N;u?((T=l.current)==null||T.resize(40),d("editor",!0),B("editor")):((N=l.current)==null||N.resize(0),d("editor",!1),h==="editor"&&o(null),B(null))},[u,d,B,o,h]);function S(T){var N;T<1?(b(!1),d("editor",!1),h==="editor"&&o(null),B(null),(N=l.current)==null||N.resize(0)):(u||(b(!0),B("editor")),x.isOpen||d("editor",!0))}function E(){return e.jsxs(e.Fragment,{children:[e.jsx(Bn,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(No,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:S,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(In,{isFullscreen:f,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,className:t.cn("absolute inset-0",!f&&"pointer-events-none")})]})]})}function I(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ti,{})}),e.jsx(n.ResizableHandle,{disabled:!u}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:l,onResize:S,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(In,{isFullscreen:f,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:v})})})]}),e.jsx("div",{ref:g,className:t.cn("absolute inset-0",!f&&"pointer-events-none")})]})}return e.jsx(n.ErrorBoundary,{FallbackComponent:n.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:E()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:m.dashboardContainerStyle,children:I()})})}function Ii(){t.useDashboardStore(m=>m.selectedCardId);const s=t.useDashboardStore(m=>m.selectedSheetId),a=t.useDashboardStore(m=>m.dashboard),{setIsVisualEditing:r,setSelectedSheetId:l}=t.useDashboardStore(m=>m.actions),u=t.useEditorStore(m=>m.editorContext),{clearEditorContext:c}=t.useEditorStore(m=>m.actions),o=n.useDashboardAppearance(),d=t.useDashboardStore(m=>m.isVisualEditing),i=t.useDashboardStore(m=>m.actions.updateFrame),x=t.useDashboardStore(m=>m.actions.updateDocumentSectionCard),h=n.useResolveExistingFrameSemanticExecutionPayload();async function v(m){var A,B,S;if((u==null?void 0:u.type)==="documentSection"){const E=n.getDocumentSectionEditorCard(m,u.cardId);if(!E){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(E)){n.ue.error("Document table sections support Table and Pivot Table");return}x(u.sheetId,u.sectionId,E,{calculatedFields:m.calculatedFields}),c(),r(!1);return}const g=s?(A=a==null?void 0:a.sheets)==null?void 0:A.some(E=>{var I;return E.id===s&&((I=E.frames)==null?void 0:I.some(T=>T.id===m.id))}):!1,y=(S=(B=a==null?void 0:a.sheets)==null?void 0:B.find(E=>{var I;return(I=E.frames)==null?void 0:I.some(T=>T.id===m.id)}))==null?void 0:S.id,b=g?s:y||null;if(!b)return;const w=n.findDashboardFrameById(a,m.id);try{const E=await h(m,{previousFrame:w});i(b,m,{semanticExecutionPayload:E}),s!==b&&l(b),r(!1)}catch(E){console.error("Failed to resolve semantic metadata on save:",E),n.ue.error(E instanceof Error?E.message:"Failed to resolve semantic metadata for this visual")}}function f(){c(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!d}),style:o.dashboardContainerStyle,children:e.jsx(Ei,{onSave:v,onClose:f})})}exports.default=Ii;