react-semaphor 0.1.423 → 0.1.425

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 (105) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +243 -91
  3. package/dist/appearance/index.cjs +1 -1
  4. package/dist/appearance/index.js +1 -1
  5. package/dist/brand-studio/index.cjs +2 -2
  6. package/dist/brand-studio/index.js +8 -8
  7. package/dist/chunks/{analyze-result-contract-D7pjjYPy.js → analyze-result-contract-DnfF8kBb.js} +434 -427
  8. package/dist/chunks/analyze-result-contract-ege_u6Nl.js +1 -0
  9. package/dist/chunks/{braces-8TRlDwDw.js → braces-BdbUk_r9.js} +1 -1
  10. package/dist/chunks/{braces-D2tStQjF.js → braces-CbO-aIwH.js} +1 -1
  11. package/dist/chunks/calendar-preferences-dialog-BLaSWhLl.js +1 -0
  12. package/dist/chunks/{calendar-preferences-dialog-t5ET6MON.js → calendar-preferences-dialog-DJwV0aqn.js} +4 -4
  13. package/dist/chunks/{catalog-field-grounding-CJKAqtiC.js → catalog-field-grounding-DcxPLns0.js} +10 -10
  14. package/dist/chunks/{switch-2bh3Hka1.js → code-editor-Bkk7s8hI.js} +7382 -6809
  15. package/dist/chunks/code-editor-CkXyNgYc.js +138 -0
  16. package/dist/chunks/{common-types-4bjoIgvm.js → common-types-ClkOI-3O.js} +4 -4
  17. package/dist/chunks/comparison-document-migration-CQJ0DZlL.js +414 -0
  18. package/dist/chunks/comparison-document-migration-Db64RWYD.js +1 -0
  19. package/dist/chunks/{index-yHe0SeLO.js → dashboard-5agU0G_D.js} +56752 -55440
  20. package/dist/chunks/dashboard-MKIqgGDp.js +1402 -0
  21. package/dist/chunks/{dashboard-briefing-launcher-S2akO-ub.js → dashboard-briefing-launcher-CII8-4qo.js} +11 -6
  22. package/dist/chunks/{dashboard-briefing-launcher-Cavd0QJb.js → dashboard-briefing-launcher-qyEVfuOm.js} +226 -209
  23. package/dist/chunks/dashboard-controls-PJpeYZHw.js +36 -0
  24. package/dist/chunks/dashboard-controls-aJY0FNPP.js +2196 -0
  25. package/dist/chunks/dashboard-input-contract-BFpERluO.js +18 -0
  26. package/dist/chunks/dashboard-input-contract-DV3cshjz.js +1 -0
  27. package/dist/chunks/{dashboard-json-Do2-pdPZ.js → dashboard-json-CzHSP6Fa.js} +16 -15
  28. package/dist/chunks/dashboard-json-DtmR5yCf.js +1 -0
  29. package/dist/chunks/date-formatter-BTTYdAik.js +1 -0
  30. package/dist/chunks/date-formatter-D-89jTjG.js +514 -0
  31. package/dist/chunks/{edit-dashboard-visual-Cw6bq4_w.js → edit-dashboard-visual-AkZzwBCV.js} +8892 -8996
  32. package/dist/chunks/edit-dashboard-visual-Cif6uDqN.js +182 -0
  33. package/dist/chunks/{index-CjzRe2su.js → index-CnujJ3fa.js} +3 -3
  34. package/dist/chunks/{index-DRlMUglg.js → index-Dpm_VET4.js} +2 -2
  35. package/dist/chunks/{index-CJdxSyQq.js → index-If0wlXGi.js} +308 -308
  36. package/dist/chunks/index-jSrCwPQz.js +31 -0
  37. package/dist/chunks/{x-CXDkqdur.js → index-xHCrHprY.js} +59 -59
  38. package/dist/chunks/{layout-grid-C0OI-MRn.js → layout-grid-B08pP7v6.js} +1 -1
  39. package/dist/chunks/{layout-grid-CiubineE.js → layout-grid-D5tYJg1-.js} +1 -1
  40. package/dist/chunks/metric-comparison-4oA4ouU9.js +354 -0
  41. package/dist/chunks/metric-comparison-nQKquVnx.js +1 -0
  42. package/dist/chunks/{palette-C4KTXOug.js → palette-C0yjT5Tv.js} +1 -1
  43. package/dist/chunks/{palette-Cp1hqZtm.js → palette-jqaAcwiQ.js} +1 -1
  44. package/dist/chunks/{save-DgMfP0j8.js → save-HCJjjzdX.js} +1 -1
  45. package/dist/chunks/{save-C__QggEE.js → save-Xdc4pnys.js} +1 -1
  46. package/dist/chunks/{search-BHsQIWBV.js → search-DHZCro8B.js} +1 -1
  47. package/dist/chunks/{search-DNCejM7Z.js → search-Dcud9ajy.js} +1 -1
  48. package/dist/chunks/{update-policy-C1pmhLz9.js → update-policy-BgONreNd.js} +1 -1
  49. package/dist/chunks/{update-policy-BCJc0oI5.js → update-policy-CY2k-pJP.js} +9 -9
  50. package/dist/chunks/{use-create-flow-overlay-state-5MDbZcs1.js → use-create-flow-overlay-state-ByOKVV2K.js} +62 -62
  51. package/dist/chunks/{use-create-flow-overlay-state-BNczg9Gj.js → use-create-flow-overlay-state-DmuReEnk.js} +2 -2
  52. package/dist/chunks/validators-B4VMLX3_.js +1 -0
  53. package/dist/chunks/{validators-PXkij33j.js → validators-Cz-XuORM.js} +123 -119
  54. package/dist/dashboard/index.cjs +1 -1
  55. package/dist/dashboard/index.js +2 -2
  56. package/dist/dashboard-authoring/index.cjs +2 -2
  57. package/dist/dashboard-authoring/index.js +6 -4
  58. package/dist/data-app-builder/index.cjs +6 -6
  59. package/dist/data-app-builder/index.js +5 -5
  60. package/dist/data-app-codegen/index.cjs +1 -1
  61. package/dist/data-app-codegen/index.js +2 -2
  62. package/dist/data-app-codegen-node/index.cjs +1 -1
  63. package/dist/data-app-codegen-node/index.js +3 -3
  64. package/dist/data-app-sdk/index.cjs +1 -1
  65. package/dist/data-app-sdk/index.js +6 -6
  66. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  67. package/dist/data-app-sdk-adapters/index.js +1 -1
  68. package/dist/data-app-sdk-validation/index.cjs +1 -1
  69. package/dist/data-app-sdk-validation/index.js +65 -68
  70. package/dist/format-utils/index.cjs +2 -2
  71. package/dist/format-utils/index.js +59 -58
  72. package/dist/index.cjs +1 -1
  73. package/dist/index.js +19 -19
  74. package/dist/style.css +1 -1
  75. package/dist/surfboard/index.cjs +1 -1
  76. package/dist/surfboard/index.js +3 -3
  77. package/dist/types/analytics-protocol.d.ts +299 -3
  78. package/dist/types/brand-studio.d.ts +2 -2
  79. package/dist/types/briefings.d.ts +65 -41
  80. package/dist/types/dashboard-assistant.d.ts +28 -7
  81. package/dist/types/dashboard-authoring.d.ts +123 -43
  82. package/dist/types/dashboard.d.ts +97 -48
  83. package/dist/types/data-app-builder.d.ts +2 -2
  84. package/dist/types/data-app-sdk.d.ts +1 -1
  85. package/dist/types/format-utils.d.ts +98 -10
  86. package/dist/types/index.js +1 -1
  87. package/dist/types/main.d.ts +229 -95
  88. package/dist/types/shared.d.ts +84 -43
  89. package/dist/types/surfboard.d.ts +99 -49
  90. package/dist/types/types.d.ts +110 -50
  91. package/package.json +2 -1
  92. package/dist/chunks/analyze-result-contract-DpDcImgk.js +0 -1
  93. package/dist/chunks/calendar-preferences-dialog-CTmeASaM.js +0 -1
  94. package/dist/chunks/contracts-CoCOpd_i.js +0 -11
  95. package/dist/chunks/contracts-CtB2VONT.js +0 -1
  96. package/dist/chunks/dashboard-controls-BJLrErjW.js +0 -2322
  97. package/dist/chunks/dashboard-controls-DzbP8AXA.js +0 -52
  98. package/dist/chunks/dashboard-json-5tWb5KD6.js +0 -1
  99. package/dist/chunks/date-formatter-B4EBSe9C.js +0 -1
  100. package/dist/chunks/date-formatter-BlhBftA9.js +0 -416
  101. package/dist/chunks/edit-dashboard-visual-Yh5YFgMF.js +0 -178
  102. package/dist/chunks/index-BPM3gDRw.js +0 -1406
  103. package/dist/chunks/switch-DMT7qf_R.js +0 -138
  104. package/dist/chunks/validators-DMlVbd1p.js +0 -1
  105. package/dist/chunks/x-B6ghREd2.js +0 -31
@@ -0,0 +1,182 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),y=require("react"),n=require("./dashboard-MKIqgGDp.js"),ae=require("./index-jSrCwPQz.js"),t=require("./code-editor-CkXyNgYc.js");require("./analyze-result-contract-ege_u6Nl.js");const Ue=require("./search-Dcud9ajy.js"),Te=require("./use-create-flow-overlay-state-DmuReEnk.js"),At=require("./card-config-utils-15sRtebL.js"),Ja=require("react-dom");require("./index-Dpm_VET4.js");require("./comparison-document-migration-Db64RWYD.js");require("../briefings/index.cjs");const Ln=require("./metric-comparison-nQKquVnx.js"),Xa=require("./palette-C0yjT5Tv.js"),Za=require("./common-types-C73-Ud1-.js");function er(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,o.get?o:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const tr=er(y);/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const sr=ae.createLucideIcon("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
7
+ * @license lucide-react v0.453.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const nr=ae.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
12
+ * @license lucide-react v0.453.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const ea=ae.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
+ * @license lucide-react v0.453.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const ta=ae.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
+ * @license lucide-react v0.453.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const As=ae.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
27
+ * @license lucide-react v0.453.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const ar=ae.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
32
+ * @license lucide-react v0.453.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const sa=ae.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
37
+ * @license lucide-react v0.453.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const rr=ae.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
42
+ * @license lucide-react v0.453.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const or=ae.createLucideIcon("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/**
47
+ * @license lucide-react v0.453.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const lr=ae.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
52
+ * @license lucide-react v0.453.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const ir=ae.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
57
+ * @license lucide-react v0.453.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const cr=ae.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
62
+ * @license lucide-react v0.453.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const dr=ae.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
67
+ * @license lucide-react v0.453.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const Mn=ae.createLucideIcon("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
72
+ * @license lucide-react v0.453.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const ur=ae.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
77
+ * @license lucide-react v0.453.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const mr=ae.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
82
+ * @license lucide-react v0.453.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const hs=ae.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
87
+ * @license lucide-react v0.453.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const ps=ae.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
92
+ * @license lucide-react v0.453.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const xr=ae.createLucideIcon("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/**
97
+ * @license lucide-react v0.453.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const hr=ae.createLucideIcon("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/**
102
+ * @license lucide-react v0.453.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const pr=ae.createLucideIcon("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
107
+ * @license lucide-react v0.453.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const na=ae.createLucideIcon("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/**
112
+ * @license lucide-react v0.453.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const fr=ae.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
117
+ * @license lucide-react v0.453.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const gr=ae.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
+ * @license lucide-react v0.453.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const br=ae.createLucideIcon("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/**
127
+ * @license lucide-react v0.453.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const jr=ae.createLucideIcon("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/**
132
+ * @license lucide-react v0.453.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const vr=ae.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
137
+ * @license lucide-react v0.453.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const yr=ae.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
+ * @license lucide-react v0.453.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const Nr=ae.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
+ * @license lucide-react v0.453.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const Cr=ae.createLucideIcon("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);function Sr({open:s,onOpenChange:a}){const[r,o]=y.useState([]),{updateDataSource:d}=t.useEditorActions(),{selectedEntities:c}=n.useAssistantContextEntities("dashboard");y.useEffect(()=>{s&&o([])},[s]);const i=p=>{o(h=>h.some(b=>n.areContextEntitiesEqual(b,p))?h.filter(b=>!n.areContextEntitiesEqual(b,p)):[...h,p])},l=()=>{o([...c])},u=()=>{o([])},x=()=>{if(r.length===0)return;const p=r[0],h=p.connectionId||"",N=p.connectionType||"",v=r.some(P=>P.type==="dataset")?"semanticDomain":"database";d({connectionId:h,connectionType:N,mode:v,selectedEntities:r}),a(!1)},m=p=>"label"in p&&p.label?p.label:p.name,f=p=>{if("description"in p&&p.description)return p.description;const h=[];return p.database&&h.push(p.database),p.schema&&h.push(p.schema),p.name&&h.push(p.name),h.join(".")},g=p=>r.some(h=>n.areContextEntitiesEqual(h,p));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:l,disabled:r.length===c.length,children:"Select All"}),e.jsx(t.Button,{variant:"outline",size:"sm",onClick:u,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((p,h)=>e.jsxs("div",{className:t.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",g(p)&&"border-primary bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:g(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:n.getEntityIcon(p.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:m(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(p)})]}),e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${h}`))})})]}),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 Oe(s){return typeof s=="string"&&s.trim().length>0?s.trim():null}function aa(s){return Array.from(new Set(s.filter(a=>!!a)))}function wr(s){const a=Oe(s.table),r=Oe(s.schema),o=Oe(s.catalog)||Oe(s.database);return a?aa([a,r?`${r}.${a}`:null,o?`${o}.${a}`:null,o&&r?`${o}.${r}.${a}`:null]):[]}function Is(s){const a=Oe(s.table)||Oe(s.tableName);return aa([Oe(s.name),Oe(s.alias),...wr({table:a,schema:Oe(s.schema)||Oe(s.schemaName),catalog:Oe(s.catalog),database:Oe(s.database)||Oe(s.databaseName)})])}function Tr(s,a){if(s.type==="dataset"){const u=Oe(s.domainId),x=Oe(a.domainId);if(u&&x&&u!==x)return!0;if(a.type==="dataset"){const m=Oe(s.id),f=Oe(a.id);if(m&&f&&m!==f)return!0;const g=Oe(a.name);if(g&&!Is(s).includes(g))return!0}return!1}const r=Oe(s.id),o=Oe(a.id);if(r&&o&&r!==o)return!0;const d=Oe(s.domainId),c=Oe(a.domainId);if(d&&c&&d!==c)return!0;const i=Oe(s.connectionId),l=Oe(a.connectionId);return!!(i&&l&&i!==l)}function ks(s,a){if(!a||!(s!=null&&s.length))return;const r=Is(a);if(r.length===0)return;const o=s.filter(c=>!Tr(c,a));for(const c of r){const i=o.find(l=>Oe(l.name)===c);if(i)return i}const d=o.filter(c=>Is(c).some(l=>r.includes(l)));return d.length===1?d[0]:void 0}function fs(s,a){const r=ks(s,a);return r?{...a,...r}:a}function Er(s,a){const r=a||[];return r.length===0?s:{...s,baseEntity:fs(r,s.baseEntity),joins:s.joins.map(o=>({...o,source:fs(r,o.source),target:fs(r,o.target)}))}}function Rn(s,a){if(!(s!=null&&s.joins.length))return[];const r=[s.baseEntity,...s.joins.flatMap(d=>[d.source,d.target])],o=[];return r.forEach(d=>{!ks(a,d)&&!ks(o,d)&&o.push(d)}),o}function Fn(){return{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}}function Ir({initialJoinPlan:s,availableDataSources:a}){const[r,o]=y.useState(()=>Er(s,a)),[d,c]=y.useState(new Set),i=()=>{const A=r.joins.length>0?Math.max(...r.joins.map(E=>E.sequence))+1:1,I={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:A,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};o({...r,joins:[...r.joins,I]}),c(new Set([...d,I.id]))},l=A=>{o({...r,joins:r.joins.filter(I=>I.id!==A)}),c(new Set([...d].filter(I=>I!==A)))},u=(A,I)=>{var F,V,R,j,T;const E=r.joins.find(L=>L.id===A);if(!E)return;const w={...E,...I};if((F=w.source)!=null&&F.name&&((V=w.target)!=null&&V.name)&&w.source.name===w.target.name){n.ue.error("Self-joins are not yet supported",{description:`Joining ${w.source.name} to itself is not currently supported. Please select a different target table.`});return}const D=r.joins.filter(L=>{var O;return L.id!==A&&L.target.name===((O=w.target)==null?void 0:O.name)});if((R=w.target)!=null&&R.name&&D.length>0){n.ue.error("Duplicate join targets are not supported",{description:`The table ${w.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const M=r.joins.map(L=>L.id===A?w:L);if((j=w.source)!=null&&j.name&&((T=w.target)!=null&&T.name)&&w.joinKeyGroups[0].keys.length===0){const L=a.find(_=>{var q;return _.name===((q=w.source)==null?void 0:q.name)}),O=a.find(_=>{var q;return _.name===((q=w.target)==null?void 0:q.name)}),B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="},z=[...w.joinKeyGroups];z[0]={...z[0],keys:[B]},w.joinKeyGroups=z,M[M.findIndex(_=>_.id===A)]=w}o({...r,joins:M})};return{joinPlan:r,expandedJoins:d,setJoinPlan:o,addJoin:i,removeJoin:l,updateJoin:u,moveJoinUp:A=>{const I=r.joins.findIndex(E=>E.id===A);if(I>0){const E=[...r.joins],w={...E[I]},D={...E[I-1]};E[I]=D,E[I-1]=w,E.forEach((F,V)=>{F.sequence=V+1});const M={...r,joins:E};o(M)}},moveJoinDown:A=>{const I=r.joins.findIndex(E=>E.id===A);if(I<r.joins.length-1){const E=[...r.joins],w={...E[I]},D={...E[I+1]};E[I]=D,E[I+1]=w,E.forEach((F,V)=>{F.sequence=V+1});const M={...r,joins:E};o(M)}},toggleJoinExpansion:A=>{const I=new Set(d);I.has(A)?I.delete(A):I.add(A),c(I)},getAvailableSourceEntities:A=>{if(r.joins.length===0)return a;const I=r.joins.findIndex(w=>w.id===A);if(I===0)return a.filter(w=>w.name===r.baseEntity.name);const E=new Set;return r.baseEntity.name&&E.add(r.baseEntity.name),r.joins.slice(0,I).forEach(w=>{E.add(w.source.name),E.add(w.target.name)}),a.filter(w=>E.has(w.name))},getAvailableTargetEntities:A=>a.filter(I=>I.name!==A),addJoinKeyGroup:A=>{const I=r.joins.find(w=>w.id===A);if(!I)return;const E=[...I.joinKeyGroups,Fn()];u(A,{joinKeyGroups:E})},updateGroupOperator:(A,I,E)=>{const w=r.joins.find(M=>M.id===A);if(!w)return;const D=[...w.joinKeyGroups];D[I]={...D[I],operator:E},u(A,{joinKeyGroups:D})},removeJoinKeyGroup:(A,I)=>{const E=r.joins.find(D=>D.id===A);if(!E)return;const w=[...E.joinKeyGroups];w.splice(I,1),u(A,{joinKeyGroups:w})},addJoinKey:(A,I)=>{const E=r.joins.find(V=>V.id===A);if(!E)return;const w=a.find(V=>V.name===E.source.name),D=a.find(V=>V.name===E.target.name),M=[...E.joinKeyGroups];M[I]||(M[I]=Fn());const F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="};M[I]={...M[I],keys:[...M[I].keys,F]},u(A,{joinKeyGroups:M})},updateJoinKey:(A,I,E,w,D)=>{const M=r.joins.find(T=>T.id===A);if(!M)return;const F=a.find(T=>T.name===M.source.name),V=a.find(T=>T.name===M.target.name),R=[...M.joinKeyGroups],j=R[I].keys[E];w==="sourceColumnName"&&F?R[I].keys[E]={...j,source:{...j.source,name:D}}:w==="targetColumnName"&&V?R[I].keys[E]={...j,target:{...j.target,name:D}}:w==="operator"&&(R[I].keys[E]={...j,operator:D}),u(A,{joinKeyGroups:R})},removeJoinKey:(A,I,E)=>{const w=r.joins.find(M=>M.id===A);if(!w)return;const D=[...w.joinKeyGroups];D[I].keys.splice(E,1),u(A,{joinKeyGroups:D})},generateSQLPreview:()=>{const A=[...r.joins].sort((w,D)=>w.sequence-D.sequence),I=r.baseEntity;if(!I.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
152
+ FROM ${I.name}`;return A.forEach(w=>{const D=a.find(V=>V.name===w.target.name);if(!D)return;const M=w.joinKeyGroups.filter(V=>V.keys&&V.keys.length>0).map(V=>{const R=V.keys.filter(j=>{var T,L,O,B;return((T=j.source)==null?void 0:T.name)&&((L=j.target)==null?void 0:L.name)&&((O=j.source)==null?void 0:O.entityName)&&((B=j.target)==null?void 0:B.entityName)}).map(j=>`${j.source.entityName}.${j.source.name} ${j.operator} ${j.target.entityName}.${j.target.name}`);return R.length>1?`(${R.join(` ${V.operator} `)})`:R[0]}).filter(Boolean),F=M.length>1?M.join(" OR "):M[0]||"condition_here";E+=`
153
+ ${w.joinType} JOIN ${D.name}
154
+ ON ${F}`}),E},isValidConfiguration:()=>!(!r.baseEntity.name||r.joins.some(w=>!w.source.name||!w.target.name)||r.joins.some(w=>w.joinKeyGroups.some(D=>D.keys.length===0))||r.joins.some(w=>w.joinKeyGroups.some(D=>D.keys.some(M=>!M.source.name||!M.target.name||!M.operator))))}}const kr=[{value:"LEFT",label:"Keep rows without a match"},{value:"INNER",label:"Only matching rows"},{value:"RIGHT",label:"Keep all target rows"},{value:"FULL",label:"Keep all rows"}],Dr={one_to_one:"One to one",one_to_many:"One to many",many_to_one:"Many to one",many_to_many:"Many to many"},Ar={one_to_one:"1 : 1",one_to_many:"1 : N",many_to_one:"N : 1",many_to_many:"N : N"},Lr=["=","<",">","<=",">="];function Mr({joinPlan:s,availableDataSources:a,onSave:r,onRemove:o,onCancel:d}){const{columnGroups:c}=n.useColumns(),i=c.filter(O=>O.entityName!==t.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:l,expandedJoins:u,setJoinPlan:x,addJoin:m,removeJoin:f,updateJoin:g,moveJoinUp:p,moveJoinDown:h,toggleJoinExpansion:N,getAvailableSourceEntities:b,getAvailableTargetEntities:v,addJoinKeyGroup:k,updateGroupOperator:P,removeJoinKeyGroup:C,addJoinKey:S,updateJoinKey:A,removeJoinKey:I,generateSQLPreview:E,isValidConfiguration:w}=Ir({initialJoinPlan:s,availableDataSources:a}),[D,M]=y.useState(new Set),[F,V]=y.useState(!1),R=O=>{const B=i.find(z=>z.entityName===O);return(B==null?void 0:B.columns)||[]},j=O=>M(B=>{const z=new Set(B);return z.has(O)?z.delete(O):z.add(O),z}),T=[];l.baseEntity.name&&T.push(l.baseEntity.name);for(const O of[...l.joins].sort((B,z)=>B.sequence-z.sequence))O.target.name&&!T.includes(O.target.name)&&T.push(O.target.name);const L=O=>{const B=O.joinKeyGroups.flatMap(q=>q.keys),z=B.find(q=>{var G,H;return((G=q.source)==null?void 0:G.name)&&((H=q.target)==null?void 0:H.name)});if(!z)return null;const _=B.length>1?` +${B.length-1}`:"";return`${z.source.name} ${z.operator||"="} ${z.target.name}${_}`};return e.jsxs("div",{className:"min-w-0 space-y-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Start from"}),e.jsxs(t.Select,{value:l.baseEntity.name,onValueChange:O=>{const B=a.find(z=>z.name===O);x({...l,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:O,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select the dataset to start from..."})}),e.jsx(t.SelectContent,{children:a.map(O=>e.jsx(t.SelectItem,{value:O.name,className:"text-[12px]",children:O.name},O.name))})]}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Every other dataset connects back to this one."})]}),T.length>0&&e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Join path"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:T.map((O,B)=>e.jsxs("span",{className:"flex items-center gap-1.5",children:[B>0&&e.jsx(n.ArrowRight,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-[4px] border px-2 py-1 leading-none ${B===0?"border-border bg-muted font-medium text-foreground":"border-border/60 text-muted-foreground"}`,children:[e.jsx(n.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate text-[11.5px] leading-none",children:O}),B===0&&e.jsx("span",{className:"shrink-0 text-[9.5px] uppercase leading-none tracking-[0.06em] text-muted-foreground",children:"BASE"})]})]},O))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["How datasets connect (",l.joins.length,")"]}),e.jsxs(t.Button,{variant:"outline",size:"xs",className:"gap-1.5",onClick:m,children:[e.jsx(n.Plus,{className:"h-3.5 w-3.5"}),"Add join"]})]}),l.joins.length===0?e.jsxs("div",{className:"rounded-[6px] border border-dashed border-border px-4 py-8 text-center",children:[e.jsx("p",{className:"text-[12.5px] font-medium text-foreground",children:"No joins yet"}),e.jsxs("p",{className:"mx-auto mt-1 max-w-[360px] text-[11.5px] leading-relaxed text-muted-foreground",children:["Add a join to connect another dataset to"," ",l.baseEntity.name||"your base dataset","."]})]}):e.jsx("div",{className:"max-h-[340px] space-y-1.5 overflow-y-auto",children:l.joins.map(O=>{var $;const B=a.find(W=>W.name===O.source.name),z=a.find(W=>W.name===O.target.name),_=u.has(O.id),q=D.has(O.id)||O.joinKeyGroups.length>1||O.joinKeyGroups.some(W=>W.operator!=="AND"),G=L(O),H=O.relationshipCardinality;return e.jsxs("div",{className:`rounded-[6px] border ${_?"border-border":"border-border/60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",onClick:()=>N(O.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[_?e.jsx(ae.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Ue.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-[12.5px] font-medium text-foreground",children:[e.jsx("span",{className:"truncate",children:O.source.name||"source"}),e.jsx(n.ArrowRight,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:O.target.name||"target"})]}),G&&e.jsx("code",{className:"hidden max-w-[180px] shrink-0 truncate rounded-[4px] bg-muted px-1.5 py-0.5 font-mono text-[10.5px] text-muted-foreground lg:inline-block",children:G})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-0.5",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>p(O.id),disabled:O.sequence===1,"aria-label":"Move join earlier",children:e.jsx(Rr,{})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>h(O.id),disabled:O.sequence===l.joins.length,"aria-label":"Move join later",children:e.jsx(Fr,{})}),e.jsxs(t.Button,{variant:"ghost",size:"sm",className:"h-6 gap-1 px-1.5 text-[11px] font-medium text-muted-foreground",onClick:()=>N(O.id),children:[e.jsx(n.Pencil,{className:"h-3 w-3"}),_?"Editing":"Edit"]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground",onClick:()=>f(O.id),"aria-label":"Remove join",children:e.jsx(ae.X,{className:"h-3.5 w-3.5"})})]})]}),_&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 pb-4 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"From"}),e.jsxs(t.Select,{value:O.source.name,onValueChange:W=>{const Q=a.find(se=>se.name===W);g(O.id,{source:{connectionId:(Q==null?void 0:Q.connectionId)||"",connectionType:(Q==null?void 0:Q.connectionType)||"none",type:(Q==null?void 0:Q.type)||"table",name:W,database:Q==null?void 0:Q.database,schema:Q==null?void 0:Q.schema}})},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:b(O.id).map(W=>e.jsx(t.SelectItem,{value:W.name,className:"text-[12px]",children:W.name},W.name))})]})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"To"}),e.jsxs(t.Select,{value:O.target.name,onValueChange:W=>{const Q=a.find(se=>se.name===W);g(O.id,{target:{connectionId:(Q==null?void 0:Q.connectionId)||"",connectionType:(Q==null?void 0:Q.connectionType)||"none",type:(Q==null?void 0:Q.type)||"table",name:W,database:Q==null?void 0:Q.database,schema:Q==null?void 0:Q.schema}})},disabled:!O.source.name,children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:O.source.name?v(O.source.name).map(W=>e.jsx(t.SelectItem,{value:W.name,className:"text-[12px]",children:W.name},W.name)):null})]})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"When a row has no match"}),e.jsxs(t.Select,{value:O.joinType,onValueChange:W=>g(O.id,{joinType:W}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kr.map(W=>e.jsx(t.SelectItem,{value:W.value,className:"text-[12px]",children:e.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:W.label}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] tracking-[0.04em] text-muted-foreground",children:W.value})]})},W.value))})]})]})]}),H&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2 rounded-[5px] border border-border/60 bg-muted/40 px-2.5 py-1.5 text-[11.5px]",children:[e.jsx("span",{className:"shrink-0 rounded-[3px] bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground",children:Ar[H]}),e.jsx("span",{className:"text-muted-foreground",children:Dr[H]}),e.jsxs("span",{className:"truncate text-muted-foreground/70",children:["(",O.source.name||"source"," →"," ",O.target.name||"target",")"]})]}),O.source.name&&O.target.name&&B&&z&&e.jsx("div",{className:"space-y-2",children:q?e.jsx(Or,{join:O,getColumnsForEntity:R,addJoinKey:S,addJoinKeyGroup:k,updateGroupOperator:P,removeJoinKeyGroup:C,updateJoinKey:A,removeJoinKey:I,canCollapse:O.joinKeyGroups.length<=1&&O.joinKeyGroups.every(W=>W.operator==="AND"),onCollapse:()=>j(O.id)}):e.jsxs(e.Fragment,{children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Match on"}),($=O.joinKeyGroups[0])!=null&&$.keys.length?e.jsx("div",{className:"min-w-0 space-y-1.5",children:O.joinKeyGroups[0].keys.map((W,Q)=>e.jsx(ra,{join:O,groupIndex:0,keyIndex:Q,conditionKey:W,getColumnsForEntity:R,updateJoinKey:A,removeJoinKey:I,showRemove:O.joinKeyGroups[0].keys.length>1},W.id||Q))}):e.jsx("p",{className:"rounded-[5px] border border-border/60 px-3 py-2 text-[11.5px] text-muted-foreground",children:"No match condition yet. Add one to define how these connect."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>S(O.id,0),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add condition"]}),e.jsxs("button",{type:"button",onClick:()=>j(O.id),className:"inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:[e.jsx(n.Settings2,{className:"h-3 w-3"}),"Advanced"]})]})]})})]})]},O.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>V(O=>!O),className:"inline-flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:[F?e.jsx(ae.ChevronDown,{className:"h-3 w-3"}):e.jsx(Ue.ChevronRight,{className:"h-3 w-3"}),"View SQL"]}),F&&e.jsx("div",{className:"rounded-[5px] border border-border/60 bg-muted/40 p-3",children:e.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] text-muted-foreground",children:E()})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border pt-4",children:[e.jsxs(t.Button,{variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",onClick:()=>{o(),d()},children:[e.jsx(n.Trash2,{className:"h-3.5 w-3.5"}),"Remove all"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"outline",size:"xs",onClick:d,children:"Cancel"}),e.jsxs(t.Button,{size:"xs",className:"gap-1.5",onClick:()=>r(l),disabled:!w(),children:["Save joins",e.jsx(n.ArrowRight,{className:"h-3.5 w-3.5"})]})]})]})]})}function Rr(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m18 15-6-6-6 6"})})}function Fr(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}function ra({join:s,groupIndex:a,keyIndex:r,conditionKey:o,getColumnsForEntity:d,updateJoinKey:c,removeJoinKey:i,showRemove:l,showOperator:u=!1}){const x=u||(o.operator||"=")!=="=";return e.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border/60 p-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs(t.Select,{value:o.source.name,onValueChange:m=>c(s.id,a,r,"sourceColumnName",m),children:[e.jsx(t.SelectTrigger,{className:"h-7 font-mono text-[11px]",children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:d(s.source.name).map(m=>e.jsx(t.SelectItem,{value:m.name,children:e.jsxs("span",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono",children:m.name}),m.dataType&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.dataType})]})},m.name))})]})}),x?e.jsx("div",{className:"w-16 shrink-0",children:e.jsxs(t.Select,{value:o.operator,onValueChange:m=>c(s.id,a,r,"operator",m),children:[e.jsx(t.SelectTrigger,{className:"h-7 justify-center px-1 font-mono text-[11px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Lr.map(m=>e.jsx(t.SelectItem,{value:m,children:m},m))})]})}):e.jsx("span",{className:"shrink-0 px-1 font-mono text-[12px] text-muted-foreground",children:"="}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs(t.Select,{value:o.target.name,onValueChange:m=>c(s.id,a,r,"targetColumnName",m),children:[e.jsx(t.SelectTrigger,{className:"h-7 font-mono text-[11px]",children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:d(s.target.name).map(m=>e.jsx(t.SelectItem,{value:m.name,children:e.jsxs("span",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono",children:m.name}),m.dataType&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.dataType})]})},m.name))})]})}),l&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>i(s.id,a,r),"aria-label":"Remove condition",children:e.jsx(ae.X,{className:"h-3.5 w-3.5"})})]})}function Or({join:s,getColumnsForEntity:a,addJoinKey:r,addJoinKeyGroup:o,updateGroupOperator:d,removeJoinKeyGroup:c,updateJoinKey:i,removeJoinKey:l,canCollapse:u,onCollapse:x}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(n.Settings2,{className:"h-3 w-3"}),"Advanced conditions"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("button",{type:"button",onClick:x,className:"text-[11px] font-medium text-muted-foreground hover:text-foreground",children:"Use simple"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>o(s.id),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add OR group"]})]})]}),s.joinKeyGroups.map((m,f)=>e.jsxs("div",{className:"space-y-2 rounded-[5px] border border-border/60 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("span",{className:"text-[11px] font-medium text-foreground",children:["Group ",f+1]}),f>0&&e.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:"OR with previous"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:"within group"}),e.jsxs(t.Select,{value:m.operator,onValueChange:g=>d(s.id,f,g),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-[76px] text-[11px]",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"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground",onClick:()=>c(s.id,f),"aria-label":"Remove group",children:e.jsx(n.Trash2,{className:"h-3.5 w-3.5"})})]})]}),m.keys.length===0?e.jsx("p",{className:"rounded-[5px] border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No conditions in this group."}):e.jsx("div",{className:"min-w-0 space-y-1.5",children:m.keys.map((g,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[p>0&&e.jsx("span",{className:"w-9 shrink-0 text-center text-[10px] font-medium text-muted-foreground",children:m.operator}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(ra,{join:s,groupIndex:f,keyIndex:p,conditionKey:g,getColumnsForEntity:a,updateJoinKey:i,removeJoinKey:l,showRemove:!0,showOperator:!0})})]},g.id||p))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",onClick:()=>r(s.id,f),children:[e.jsx(n.Plus,{className:"h-3 w-3"})," Add condition"]})]},m.id))]})}function oa({children:s,open:a,onOpenChange:r,joinPlan:o,availableDataSources:d,onRemove:c,onSave:i,onCancel:l}){return e.jsxs(n.Dialog,{open:a,onOpenChange:r,children:[e.jsxs(n.DialogContent,{className:"max-h-[88vh] w-[calc(100vw-2rem)] max-w-4xl overflow-y-auto overflow-x-hidden",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{className:"text-[15px] font-semibold tracking-tight",children:"How datasets connect"}),e.jsx(n.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Datasets joined together so a card can use fields from all of them."})]}),e.jsx(Mr,{joinPlan:o,availableDataSources:d,onSave:i,onCancel:l,onRemove:c})]}),s]})}function Pr({joins:s,baseEntityId:a,availableDataSources:r,generateSQLPreview:o}){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 d=[...s].sort((i,l)=>i.sequence-l.sequence),c=r.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(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"})]}),d.map(i=>{const l=r.find(u=>u.name===i.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(n.Badge,{variant:"outline",className:"text-xs",children:i.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(n.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((d,c)=>d.sequence-c.sequence).map((d,c)=>{const i=r.find(x=>x.name===d.source.name),l=r.find(x=>x.name===d.target.name),u=d.joinKeyGroups.reduce((x,m)=>x+m.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:d.joinType}),e.jsxs(n.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[u," condition",u>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",l==null?void 0:l.name]})]},d.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:o()})})]})]})}function Vr({open:s,onOpenChange:a,variant:r="button"}={}){var k,P;const o=t.useEditorStore(C=>C.card),{autoJoinMetadata:d}=n.useEditorCardQuery(o),c=t.useEditorStore(C=>C.actions.updateCardConfig),i=((k=o==null?void 0:o.config)==null?void 0:k.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,u]=y.useState(!1),x=s!==void 0,m=x?s:l,f=x?a:u,g=((P=o==null?void 0:o.dataSource)==null?void 0:P.selectedEntities)||[],p=C=>{c(o.id,{...o==null?void 0:o.config,joinPlan:C}),f(!1)},h=()=>{c(o.id,{...o==null?void 0:o.config,joinPlan:void 0})},N=()=>{f(!1)},b=()=>{const C=[...i.joins].sort((I,E)=>I.sequence-E.sequence),S=i.baseEntity;if(!S.name)return"SELECT * FROM table -- Please select a base entity";let A=`SELECT *
155
+ FROM ${S.name}`;return C.forEach(I=>{const E=g.find(M=>M.name===I.target.name);if(!E)return;const w=I.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const F=M.keys.filter(V=>{var R,j,T,L;return((R=V.source)==null?void 0:R.name)&&((j=V.target)==null?void 0:j.name)&&((T=V.source)==null?void 0:T.entityName)&&((L=V.target)==null?void 0:L.entityName)}).map(V=>`${V.source.entityName}.${V.source.name} ${V.operator} ${V.target.entityName}.${V.target.name}`);return F.length>1?`(${F.join(` ${M.operator} `)})`:F[0]}).filter(Boolean),D=w.length>1?w.join(" OR "):w[0]||"condition_here";A+=`
156
+ ${I.joinType} JOIN ${E.name}
157
+ ON ${D}`}),A};if(g.length<2)return null;const v=i.joins.length>0&&e.jsx(t.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Pr,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:g,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:C=>{C.stopPropagation(),f(!0)},children:[e.jsx(n.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs("button",{type:"button",onClick:()=>f(!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:i.joins.length===0?"Configure joins":`${i.joins.length} ${i.joins.length===1?"join":"joins"}`}),(d==null?void 0:d.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"]})]})}),v]})}),e.jsx(oa,{open:m,onOpenChange:f,joinPlan:i,availableDataSources:g,onSave:p,onCancel:N,onRemove:h,children:e.jsx("div",{})})]})}function Br(){var D,M,F,V,R,j,T;const[s,a]=y.useState(!1),[r,o]=y.useState(!1),[d,c]=y.useState(!1),i=t.useEditorStore(L=>L.card.dataSource),l=t.useEditorStore(L=>L.card),u=t.useEditorStore(L=>L.isDevMode),{updateCardConfig:x,updateDataSource:m}=t.useEditorActions(),{autoJoinMetadata:f}=n.useEditorCardQuery(l),p={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...i,selectedEntities:(i==null?void 0:i.selectedEntities)||[]},h=n.toEntityArray(p.selectedEntities),N=h.length,b=N===0?"Choose dataset":N===1?gs(h[0]):`${N} datasets`,v=((F=(M=(D=l==null?void 0:l.config)==null?void 0:D.joinPlan)==null?void 0:M.joins)==null?void 0:F.length)??0,k=Rn((V=l==null?void 0:l.config)==null?void 0:V.joinPlan,h),P=k.length>0,C=!u&&(N>1||v>0),S=!!(f!=null&&f.autoResolved);((j=(R=f==null?void 0:f.resolvedJoinPlan)==null?void 0:R.joins)==null?void 0:j.length)??((T=f==null?void 0:f.relationshipsUsed)==null||T.length);const A=v>0?`${v} join${v===1?"":"s"}`:N<2?null:S?"auto":null,I=L=>{var B;const O=h.filter(z=>!n.areContextEntitiesEqual(z,L));l&&Rn((B=l.config)==null?void 0:B.joinPlan,O).length>0&&x(l.id,{...l.config,joinPlan:void 0}),m({...p,selectedEntities:O})},E=()=>{l&&x(l.id,{...l.config,joinPlan:void 0})},w=()=>{m({...p,selectedEntities:n.dedupeContextEntities([...h,...k])})};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:b}),A&&e.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:["· ",A]}),e.jsx(ae.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:N})]}),N===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:h.map((L,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:gs(L)}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:_r(L)})]}),e.jsx("button",{type:"button",onClick:()=>I(L),"aria-label":`Remove ${gs(L)}`,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(ae.X,{className:"h-3 w-3"})})]},`${L.connectionId}-${L.name}-${O}`))}),e.jsxs("button",{type:"button",onClick:()=>{a(!1),o(!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"]})]}),C&&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"})}),P?e.jsxs("div",{className:"space-y-2 rounded-control border border-amber-300/70 bg-amber-50/70 p-2.5 text-[11px] text-amber-950 dark:border-amber-700/70 dark:bg-amber-950/20 dark:text-amber-100",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.TriangleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium",children:[v," saved ",v===1?"join":"joins"," need attention"]}),e.jsxs("p",{className:"mt-0.5 leading-relaxed text-amber-900/80 dark:text-amber-100/80",children:[k.map(L=>L.name).join(", ")," is no longer selected, but the saved join still affects this card."]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:E,className:"rounded-control border border-amber-500/60 bg-background px-2 py-1 text-[11px] font-medium text-foreground transition-colors hover:bg-amber-100 dark:bg-background dark:hover:bg-amber-950/60",children:"Remove saved join"}),e.jsx("button",{type:"button",onClick:w,className:"rounded-control px-1 py-1 text-[11px] font-medium text-amber-900 transition-colors hover:underline dark:text-amber-100",children:"Re-add dataset"})]})]}):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:v>0?`${v} ${v===1?"join":"joins"}`:"Configure joins"}),S&&v===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:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:r,onOpenChange:o,dataSource:p}),C&&!P&&e.jsx("div",{className:"hidden",children:e.jsx(Vr,{open:d,onOpenChange:c})})]})}function gs(s){return"label"in s&&s.label?s.label:s.name||"Dataset"}function _r(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 la({isVisible:s}){Te.useSyncLegacyEditorState();const[a,r]=y.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(Br,{})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(n.FieldsSection,{})}),e.jsx(Sr,{open:a,onOpenChange:r})]})}function ia({storeValue:s,defaultValue:a="",onStoreUpdate:r,delay:o=300}){const[d,c]=y.useState(s??a),i=y.useRef(null),l=y.useRef(d),u=y.useRef(s),x=y.useRef(!1),m=y.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null),x.current&&l.current!==(u.current??a)&&(r(l.current),u.current=l.current)},[a,r]);y.useEffect(()=>{if(s!==u.current){i.current&&(clearTimeout(i.current),i.current=null);const g=s??a;c(g),l.current=g,u.current=s,x.current=!1}},[s,a]),y.useEffect(()=>{if(x.current)return i.current=setTimeout(()=>{m()},o),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[o,m,d]),y.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=y.useCallback(g=>{const p=g??a;x.current=!0,l.current=p,c(p)},[a]);return{value:d,onChange:f,flush:m}}const zr=300;function qr(){const s=t.useEditorStore(v=>v.card.sql),a=t.useEditorStore(v=>v.sqlGen),r=t.useEditorStore(v=>v.card),o=Te.useEffectiveEditorCardType(),{setCardSql:d,setSqlGen:c,setRunSql:i}=t.useEditorActions(),l=y.useMemo(()=>o!==r.type?{...r,type:o}:r,[r,o]),{queryKey:u}=n.useEditorCardQuery(l),x=n.useQueryClient(),m=y.useRef(u);m.current=u;const f=y.useRef(a);f.current=a;const g=y.useCallback(v=>{d(v)},[d]),{value:p,onChange:h,flush:N}=ia({storeValue:s,defaultValue:"",onStoreUpdate:g,delay:zr});y.useEffect(()=>Te.registerPendingEditorDraftFlusher(N),[N]);function b(v){h(v),t.isObjectEmpty(f.current)||c({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!p&&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:p??"",onValueChange:b,language:"sql-jinja",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:v=>{v.key==="Enter"&&v.shiftKey&&(v.preventDefault(),Te.flushPendingEditorDrafts(),setTimeout(()=>{x.removeQueries({queryKey:m.current,exact:!0}),i(!0)},0))}})]})}const $r=300;function Kr(){const s=t.useEditorStore(g=>g.card.python),a=t.useEditorStore(g=>g.card),r=Te.useEffectiveEditorCardType(),{setCardPython:o,setRunSql:d}=t.useEditorActions(),c=y.useMemo(()=>r!==a.type?{...a,type:r}:a,[a,r]),{queryKey:i}=n.useEditorCardQuery(c),l=n.useQueryClient(),u=y.useRef(i);u.current=i;const{value:x,onChange:m,flush:f}=ia({storeValue:s,defaultValue:n.PYTHON_DEFAULT_CODE,onStoreUpdate:o,delay:$r});return y.useEffect(()=>Te.registerPendingEditorDraftFlusher(f),[f]),e.jsx(t.CodeEditor,{value:x??"",onValueChange:m,language:"python",embedded:!0,flushGutter:!0,wrapLines:!0,onKeyDown:g=>{g.key==="Enter"&&g.shiftKey&&(g.preventDefault(),Te.flushPendingEditorDrafts(),setTimeout(()=>{l.removeQueries({queryKey:u.current,exact:!0}),d(!0)},0))}})}const Ur=/\{\{-?\s*filters\s*\|\s*where\s*-?\}\}/i,Gr=/\{\{-?\s*filters\s*\|\s*and\s*-?\}\}/i,Hr=/\bwhere\b/i;function Qr(s){return s!=null&&s.trim()?Ur.test(s)||Gr.test(s):!1}function Wr(s){return!(s!=null&&s.trim())||Qr(s)?null:Hr.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 Yr(s){const{request:a,mode:r="draft",currentSql:o,selectedTableName:d,selectedSchemaName:c,selectedDatabaseName:i}=s,l=[i?`Database: ${i}`:"",c?`Schema: ${c}`:"",d?`Table: ${d}`:""].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"&&o?"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.",l.length>0?`Context:
158
+ ${l.join(`
159
+ `)}`:"",o?r==="refine"?`Current SQL (must refine):
160
+ ${o}`:`Current SQL (revise if useful):
161
+ ${o}`:"",`User request:
162
+ ${a}`].filter(Boolean).join(`
163
+
164
+ `)}function Jr(s){const{request:a,failedSql:r,errorMessage:o,errorCode:d,selectedDatabaseName:c,selectedSchemaName:i,selectedTableName:l,contextEntityLabels:u}=s,x=[c?`Database: ${c}`:"",i?`Schema: ${i}`:"",l?`Table: ${l}`:"",u.length>0?`Selected context entities: ${u.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
+ ${x.join(`
166
+ `)}`:"",`Original user request:
167
+ ${a}`,`Previous SQL draft:
168
+ ${r}`,`Validation failure${d?` (${d})`:""}:
169
+ ${o}`].filter(Boolean).join(`
170
+
171
+ `)}function Xr(s,a){typeof window>"u"||window.dispatchEvent(new CustomEvent("semaphor:inline-query-writer",{detail:{event:s,...a,timestamp:Date.now()}}))}const bs={runId:0,phase:"idle",attempt:0,activeStep:"",timelineSteps:[],lastValidation:null,finalOutcome:"idle",hasTools:!1};function Zr(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 On(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 Pn(s){return s==="getTableColumns"?"Discovering columns":s==="getDomainRelationships"?"Resolving relationships":s==="getChartSQLSyntax"?"Reviewing SQL syntax":s==="getUserSql"?"Inspecting current query":"Analyzing context"}function eo(s,a){return s===n.SELF_HEAL_TIMELINE_STEP&&a>0?`${n.SELF_HEAL_TIMELINE_STEP} ${a}/${n.MAX_SELF_HEAL_ATTEMPTS}`:s}function ss(s){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Vn(s){var a;for(let r=s.length-1;r>=0;r-=1){const o=s[r];if(o.role!=="user")continue;const d=(a=o.metadata)==null?void 0:a.inlineRunToken;if(typeof d=="string"&&d.length>0)return d}}function to(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 o=s.match(/```[\w-]*\s*([\s\S]*?)```/i);return o!=null&&o[1]?o[1].trim():/^(select|with|insert|update|delete)\b/i.test(a)?a:""}function Bn(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 o=r.parts.length-1;o>=0;o-=1){const d=r.parts[o];if((d==null?void 0:d.type)!=="text"||typeof(d==null?void 0:d.text)!="string")continue;const c=to(d.text);if(c)return c}}return""}function so({currentSql:s,currentPython:a,selectedDatabaseName:r,selectedSchemaName:o,selectedTableName:d,onApplySql:c,onOpenFullAssistant:i}){var Pt,Vt;const{authToken:l,tokenProps:u}=n.useSemaphorContext(),x=(Pt=n.useDashboardQuery().data)==null?void 0:Pt.assistantProfileId,m=t.useEditorStore(Y=>Y.isDevMode),f=t.useEditorStore(Y=>Y.selectedConnectionId),g=t.useEditorStore(Y=>{var X;return(X=Y.card.dataSource)==null?void 0:X.selectedEntities}),p=t.useAIInteractionStore(Y=>Y.currentAIContext.selectedEntities),h=p.length,{setCurrentAIContext:N}=t.useAIActions(),[b,v]=y.useState(""),[k,P]=y.useState(""),[C,S]=y.useState(""),[A,I]=y.useState("draft"),[E,w]=y.useState("draft"),[D,M]=y.useState(""),[F,V]=y.useState(!1),[R,j]=y.useState({status:"idle"}),[T,L]=y.useState(bs),[O,B]=y.useState(!1),[z,_]=y.useState(()=>ss("inline-query-session")),q=y.useRef(null),G=y.useRef(null),H=y.useRef(null),$=y.useRef(0),W=y.useRef(0),Q=y.useRef(ss("inline-run-token")),se=y.useRef(z),ue=y.useRef(new Set),pe=y.useRef(new Map),ge=y.useRef(0),ve=y.useRef(""),Pe=y.useRef(!1),Ve=y.useRef(!1),ee=y.useRef(bs),xe=y.useRef(!1),Ee=y.useRef(null),qe=y.useRef(()=>{}),$e=(Vt=u.apiServiceUrl)==null?void 0:Vt.replace(/\/$/,""),ce=$e?`${$e}/v1/sql/validate`:"/v1/sql/validate",Re=y.useCallback(Y=>{L(X=>{const Z=Y(X);return ee.current=Z,Z})},[]),we=y.useCallback((Y,X)=>{Re(Z=>Z.runId===Y?X(Z):Z)},[Re]),ie=y.useCallback(Y=>W.current===Y&&!ue.current.has(Y),[]),K=y.useCallback((Y,X,Z)=>{we(Y,be=>{const fe=be.timelineSteps.includes(X)?be.timelineSteps:[...be.timelineSteps,X];return{...be,phase:(Z==null?void 0:Z.phase)||be.phase,attempt:typeof(Z==null?void 0:Z.attempt)=="number"?Z.attempt:be.attempt,activeStep:X,timelineSteps:fe,finalOutcome:(Z==null?void 0:Z.finalOutcome)||be.finalOutcome,hasTools:Z!=null&&Z.hasTools?!0:be.hasTools}})},[we]),le=y.useCallback(()=>{const Y=W.current+1,X=ss("inline-run-token"),Z=ss("inline-query-session");return W.current=Y,Q.current=X,se.current=Z,_(Z),ue.current=new Set,pe.current=new Map,ge.current=0,ve.current="",xe.current=!1,Re(()=>({runId:Y,phase:"drafting",attempt:0,activeStep:"Drafting SQL",timelineSteps:["Drafting SQL"],lastValidation:null,finalOutcome:"drafting",hasTools:!1})),{runId:Y,runToken:X,chatSessionId:Z}},[Re]),me=y.useCallback(()=>{if(Pe.current||Ve.current||h>0)return;const Y=g||[];if(Y.length===0)return;const X=t.useAIInteractionStore.getState().currentAIContext;N({...X,selectedEntities:Y}),Ve.current=!0},[h,g,N]),te=y.useCallback(()=>{Pe.current=!0},[]),de=y.useCallback((Y,X,Z)=>{Xr(Y,{runId:X,attemptCount:typeof(Z==null?void 0:Z.attemptCount)=="number"?Z.attemptCount:ge.current,errorCode:Z==null?void 0:Z.errorCode,hasTools:typeof(Z==null?void 0:Z.hasTools)=="boolean"?Z.hasTools:T.hasTools,entityCount:h,finalOutcome:(Z==null?void 0:Z.finalOutcome)||T.finalOutcome})},[h,T.finalOutcome,T.hasTools]),Le=y.useCallback((Y,X)=>{const Z=H.current;if(!Z)return;const be={inlineRunToken:X};Z({role:"user",parts:[{type:"text",text:Y}],metadata:be},{metadata:be})},[]);y.useEffect(()=>{const Y=Ee.current;!Y||Y.sessionId!==z||(Ee.current=null,Le(Y.message,Y.runToken))},[z,Le]);const Me=z,Qe=y.useCallback(async({toolCall:Y})=>{var Ye,nt,st,_e,He,Tt;if(Me!==se.current)return;const X=String(Y.toolName||"").trim();if(!X)return;const Z=W.current;if(!ie(Z)){(Ye=G.current)==null||Ye.call(G,{tool:X,toolCallId:Y.toolCallId,output:{status:"error",message:"Inline run is no longer active; ignoring tool output."}});return}if(X==="getUserSql"){K(Z,Pn(X),{hasTools:!0}),de("inline_tool_step",Z,{hasTools:!0}),(nt=G.current)==null||nt.call(G,{tool:X,toolCallId:Y.toolCallId,output:{status:"success",sql:s||"",python:a||""}});return}const be=n.INLINE_BLOCKED_MUTATING_TOOLS.has(X),fe=n.INLINE_ALLOWED_READ_ONLY_TOOLS.has(X);if(be||!fe){(st=G.current)==null||st.call(G,{tool:X,toolCallId:Y.toolCallId,output:{status:"error",message:"This action is unavailable in inline draft mode. Open Full Assistant for this action."}});return}const ye=Pn(X);K(Z,ye,{phase:T.phase==="self-healing"?"self-healing":"drafting",hasTools:!0}),de("inline_tool_step",Z,{hasTools:!0});const Ke=((_e=Y.input)==null?void 0:_e.sql)??((He=Y.args)==null?void 0:He.sql);typeof Ke=="string"&&Ke.trim().length>0&&(xe.current=!1,S(Ke.trim())),(Tt=G.current)==null||Tt.call(G,{tool:X,toolCallId:Y.toolCallId,output:{status:"success",message:"Read-only tool result received."}})},[a,s,de,T.phase,ie,Me,K]),re=y.useCallback(({message:Y,messages:X})=>{if(Me!==se.current)return;const Z=Vn(X);if(!Z||Z!==Q.current)return;const be=W.current;if(!ie(be))return;const fe=Bn([Y])||Bn(X);if(fe){xe.current=!1,S(fe.trim());return}xe.current&&ee.current.phase==="self-healing"&&qe.current(be)},[ie,Me]),je=y.useCallback(Y=>{if(Me!==se.current)return;const X=W.current;ie(X)&&xe.current&&ee.current.phase==="self-healing"&&qe.current(X)},[ie,Me]),{setMessages:Ce,sendMessage:ne,addToolResult:Ie,status:ke,stop:Be,error:We,clearError:Se}=n.useChat({id:z,transport:new n.DefaultChatTransport({api:`${u.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${l==null?void 0:l.accessToken}`}),body:()=>{const Y=t.useAIInteractionStore.getState();return{assistantId:"editor-assistant",assistantProfileId:x,isDevMode:m,aiContext:Y.currentAIContext,reasoningEffort:Y.reasoningEffort,showReasoning:!1}},credentials:"omit",prepareSendMessagesRequest:({messages:Y,body:X,requestMetadata:Z})=>{const be=Z==null?void 0:Z.inlineRunToken,fe=Vn(Y);return{body:{...X,inlineRunToken:be||fe,messages:t.cleanupIncompleteMessages(Y)}}}}),onToolCall:Qe,onFinish:re,onError:je,sendAutomaticallyWhen:n.lastAssistantMessageIsCompleteWithToolCalls});G.current=Ie,H.current=ne;const De=!["ready","error"].includes(ke),et=(We==null?void 0:We.message)||"Unable to generate a SQL draft right now. Try again.",Fe=y.useCallback(Y=>{const X=W.current,Z=ee.current.phase;if(!(Z==="drafting"||Z==="self-healing"||Z==="validating")){Y==="stopped"&&De&&Be();return}ue.current.add(X),xe.current=!1,$.current+=1,ve.current="",j({status:"idle"}),S(""),Se(),Ce([]),we(X,fe=>({...fe,phase:"idle",activeStep:"",finalOutcome:"cancelled"})),de("inline_self_heal_stopped",X,{finalOutcome:"cancelled"}),(De||Y==="stopped")&&Be()},[Se,de,De,Ce,Be,we]),Gt=y.useCallback(async(Y,X)=>{var be;if(!ie(X))return null;const Z=$.current+1;$.current=Z,K(X,"Validating SQL",{phase:"validating"}),j({status:"validating"});try{const fe=await t.postRequestRegular(ce,(l==null?void 0:l.accessToken)||"",{sql:Y,connectionId:f||void 0});if($.current!==Z||!ie(X))return null;if((fe==null?void 0:fe.valid)===!0)return j({status:"valid",message:"SQL validation passed."}),we(X,Ye=>({...Ye,phase:"ready",finalOutcome:"validated",lastValidation:{valid:!0}})),de("inline_draft_validated",X,{finalOutcome:"validated"}),{status:"valid"};const ye=Zr(fe==null?void 0:fe.errorCode)||"UNKNOWN",Ke=typeof(fe==null?void 0:fe.error)=="string"&&fe.error||typeof((be=fe==null?void 0:fe.details)==null?void 0:be.error)=="string"&&fe.details.error||"SQL validation failed. Please revise the query draft.";return j({status:"invalid",message:Ke,errorCode:ye}),we(X,Ye=>({...Ye,lastValidation:{valid:!1,error:Ke,errorCode:ye}})),de("inline_validation_failed",X,{errorCode:ye,finalOutcome:"validation_failed"}),{status:"invalid",error:Ke,errorCode:ye}}catch(fe){if($.current!==Z||!ie(X))return null;const ye=t.getRequestErrorMessage(fe,"Validation service unavailable. You can still replace and run.");return j({status:"error",message:ye,errorCode:"SQL_CONNECTION_ERROR"}),we(X,Ke=>({...Ke,phase:"error",finalOutcome:"error",lastValidation:{valid:!1,error:ye,errorCode:"SQL_CONNECTION_ERROR"}})),{status:"error",error:ye,errorCode:"SQL_CONNECTION_ERROR"}}},[l==null?void 0:l.accessToken,de,ie,f,ce,we,K]),Ct=y.useCallback((Y,X,Z,be)=>{let fe=Z,ye="validation_failed",Ke="Validating SQL";X==="attempt_limit"?(fe=`Couldn't auto-fix after ${n.MAX_SELF_HEAL_ATTEMPTS} attempts. ${Z}`,ye="self_heal_exhausted",Ke=`Auto-fix stopped (${n.MAX_SELF_HEAL_ATTEMPTS} attempts)`):X==="duplicate"&&(fe=`Auto-fix stopped (repeated validation failure). ${Z}`,ye="self_heal_duplicate_stopped",Ke="Auto-fix stopped (repeated failure)"),j({status:"invalid",message:fe,errorCode:be}),K(Y,Ke,{phase:"error",finalOutcome:ye}),we(Y,Ye=>({...Ye,phase:"error",finalOutcome:ye,lastValidation:{valid:!1,error:fe,errorCode:be}})),X!=="terminal"&&de("inline_self_heal_stopped",Y,{errorCode:be,finalOutcome:ye}),xe.current=!1},[de,we,K]),ds=y.useCallback(Y=>{const X="Auto-fix stopped (no SQL returned). Open Full Assistant to continue.",Z="self_heal_no_draft";j({status:"invalid",message:X,errorCode:"UNKNOWN"}),K(Y,"Auto-fix stopped (no SQL returned)",{phase:"error",finalOutcome:Z}),we(Y,be=>({...be,phase:"error",finalOutcome:Z,lastValidation:{valid:!1,error:X,errorCode:"UNKNOWN"}})),de("inline_self_heal_stopped",Y,{errorCode:"UNKNOWN",finalOutcome:Z}),xe.current=!1},[de,we,K]);qe.current=ds,y.useEffect(()=>{const Y=C.trim(),X=W.current;if(!Y){if($.current+=1,ve.current="",ee.current.phase==="error")return;j({status:"idle"});return}if(!ie(X)||De)return;const Z=`${X}:${ge.current}:${On(Y)}`;if(ve.current===Z)return;ve.current=Z;let be=!1;return(async()=>{const ye=await Gt(Y,X);if(!ye||be||!ie(X)||ye.status!=="invalid")return;if(!n.RECOVERABLE_SQL_ERROR_CODES.has(ye.errorCode)){Ct(X,"terminal",ye.error,ye.errorCode);return}const Ke=`${On(Y)}::${ye.errorCode}`,Ye=(pe.current.get(Ke)||0)+1;if(pe.current.set(Ke,Ye),Ye>=2){Ct(X,"duplicate",ye.error,ye.errorCode);return}if(ge.current>=n.MAX_SELF_HEAL_ATTEMPTS){Ct(X,"attempt_limit",ye.error,ye.errorCode);return}const nt=ge.current+1;ge.current=nt,K(X,n.SELF_HEAL_TIMELINE_STEP,{phase:"self-healing",attempt:nt}),de("inline_self_heal_attempt",X,{attemptCount:nt,errorCode:ye.errorCode}),xe.current=!0,Se(),Ce([]),S("");const st=p.map(He=>{const Tt=He!=null&&He.database?`${He.database}.`:"",es=He!=null&&He.schema?`${He.schema}.`:"",Ae=(He==null?void 0:He.name)||"unknown";return`${Tt}${es}${Ae}`}),_e=Jr({request:k,failedSql:Y,errorMessage:ye.error,errorCode:ye.errorCode,selectedDatabaseName:r||"",selectedSchemaName:o||"",selectedTableName:d||"",contextEntityLabels:st});Le(_e,Q.current)})(),()=>{be=!0}},[Se,p,de,De,ie,k,C,r,o,d,Le,Ce,Ct,K,Gt]);const ut=(s==null?void 0:s.trim())||"",St=y.useCallback((Y="draft")=>{if(De)return;const X=b.trim();if(!X)return;const Z=Y==="refine"&&ut?"refine":"draft",be=Z==="refine"?ut:"",fe=ut,{runId:ye,runToken:Ke,chatSessionId:Ye}=le();de("inline_draft_started",ye,{attemptCount:0,hasTools:!1,finalOutcome:"drafting"}),me(),Se(),P(X),S(""),I(Z),M(be),V(!1),j({status:"idle"}),$.current+=1,Ce([]),B(!0);const nt=Yr({request:X,mode:Z,currentSql:fe,selectedTableName:d||"",selectedSchemaName:o||"",selectedDatabaseName:r||""});Ee.current={sessionId:Ye,message:nt,runToken:Ke}},[le,Se,ut,de,De,b,me,r,o,d,Ce]),Ht=y.useCallback(Y=>{const X=C.trim();X&&(c(X,Y),Y||B(!1))},[c,C]),bt=C.trim().length>0,Lt=["valid","invalid","error"].includes(R.status),jt=bt&&Lt,tt=R.status==="invalid",Qt=R.status==="validating",Mt=bt&&k.length>0&&k===b.trim(),mt=ut.length>0,Wt=b.length>0,it=Mt&&A==="draft",xt=Mt&&A==="refine"&&D===ut,ht=E==="refine"&&!mt?"draft":E,Yt=(ht==="refine"?xt:it)?"Open composer preview":"Generate composer SQL",Jt=b.trim().length>0||k.trim().length>0||bt||R.status!=="idle"||T.timelineSteps.length>0,wt=y.useCallback((Y="draft")=>{if(De)return;if((Y==="refine"?xt:it)&&!O){me(),B(!0);return}St(Y)},[it,xt,St,De,O,me]),Rt=y.useCallback(()=>{me(),B(!0)},[me]),Ft=y.useCallback(Y=>{Fe("cancelled"),v(Y)},[Fe]),Xt=y.useCallback(()=>{De||(Fe("cancelled"),xe.current=!1,$.current+=1,ve.current="",ge.current=0,v(""),P(""),S(""),I("draft"),w("draft"),M(""),V(!1),j({status:"idle"}),Se(),Ce([]),Re(Y=>({...bs,runId:Y.runId})))},[Fe,Se,De,Ce,Re]),pt=y.useCallback(Y=>{Y||Fe("cancelled"),B(Y)},[Fe]),Ot=T.timelineSteps.findIndex(Y=>Y===T.activeStep),Zt=T.phase==="self-healing"?"Fixing validation issue":T.phase==="validating"?"Validating SQL":T.activeStep||"Drafting SQL",vt=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:Y=>Ft(Y.target.value),onFocus:Rt,onClick:Rt,onKeyDown:Y=>{Y.key==="Enter"&&(Y.preventDefault(),wt(ht))},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",Wt?"pr-[56px]":"pr-9"].join(" ")}),e.jsxs(t.Popover,{open:O,onOpenChange:pt,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:[Wt&&e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:Y=>{Y.preventDefault(),Fe("cancelled"),v("")},disabled:De,"aria-label":"Clear input",title:"Clear input",children:e.jsx(ae.X,{className:"size-3.5"})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"size-6 p-0",onClick:Y=>{Y.preventDefault(),wt(ht)},disabled:De,"aria-label":Yt,title:Yt,children:e.jsx(n.SendHorizontal,{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:Y=>{Y.preventDefault()},onInteractOutside:Y=>{var Z;const X=Y.target;X&&((Z=q.current)!=null&&Z.contains(X))&&Y.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]",ht==="draft"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>{w("draft"),V(!1)},children:"Draft New"}),e.jsx(t.Button,{type:"button",variant:"ghost",className:["h-6 rounded-[4px] px-2 text-[12px]",ht==="refine"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"].join(" "),onClick:()=>w("refine"),disabled:!mt,children:"Refine"})]}),e.jsx(n.AssistantContextEntityControls,{mode:"full",compact:!0,inlineLayout:!0,inlineTriggerFirst:!0,triggerVariant:"outline",triggerIconOnly:!1,triggerLabel:"Context",onSelectionChange:te})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[De&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>{Fe("stopped")},children:"Stop"}),!De&&e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:Xt,disabled:!Jt,children:"Clear"})]})]}),T.timelineSteps.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[T.timelineSteps.map((Y,X)=>{const Z=Y===T.activeStep&&["drafting","validating","self-healing"].includes(T.phase),be=!Z&&Ot>=0&&X<Ot;return e.jsx("span",{className:["rounded-full border px-2 py-0.5 text-[11px]",Z?"border-foreground/30 bg-foreground/10 text-foreground":be?"border-border/60 bg-muted/20 text-muted-foreground":"border-border/50 bg-background text-muted-foreground/80"].join(" "),children:eo(Y,T.attempt)},`${Y}-${X}`)}),vt&&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]",vt.className].join(" "),children:vt.label})}),e.jsx(t.TooltipContent,{side:"top",align:"start",className:"max-w-[680px] whitespace-pre-wrap break-words text-xs",children:vt.detail})]})})]}),(De||T.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"}),Zt]}),We&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:et}),A==="refine"&&D&&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:()=>V(Y=>!Y),children:F?"Hide base SQL":"View base SQL"})]}),F&&e.jsx("div",{className:"max-h-[120px] overflow-auto rounded-[5px] border border-border/60",children:e.jsx(t.CodeEditor,{value:D,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Base SQL"})})]}),jt?e.jsxs("div",{className:"space-y-1",children:[A==="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:C,onValueChange:()=>{},language:"sql",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Drafted SQL"})})]}):bt?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."}):!De&&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:i,children:"Open Full Assistant"}),e.jsx(t.Button,{variant:"secondary",size:"xs",disabled:De||!jt,onClick:()=>Ht(!1),children:"Replace SQL"}),e.jsx(t.Button,{size:"xs",disabled:De||!jt||Qt||tt,onClick:()=>Ht(!0),children:"Replace & Run"})]})]})})]})]})}function no(){var Pe,Ve;const s=n.useQueryClient(),[a,r]=y.useState(!1),o=t.useEditorStore(ee=>ee.frame),d=t.useEditorStore(ee=>ee.card);t.useEditorStore(ee=>ee.isShowingVisual),t.useEditorStore(ee=>ee.selectedConnectionId),t.useEditorStore(ee=>ee.tempQueryData);const c=t.useEditorStore(ee=>ee.selectedDatabaseName);t.useEditorStore(ee=>ee.selectedDatamodelId);const i=t.useEditorStore(ee=>ee.selectedSchemaName);t.useEditorStore(ee=>ee.showAIDialog);const l=t.useEditorStore(ee=>ee.selectedTableName),u=t.useDashboardStore(ee=>{var xe,Ee;return((Ee=(xe=ee.dashboard)==null?void 0:xe.filters)==null?void 0:Ee.length)??0}),x=t.useEditorStore(ee=>ee.inlineFilterValuesMap[(d==null?void 0:d.id)??""]),m=y.useMemo(()=>n.findCustomVisualConfigCard(o,d),[o,d]),{manifest:f}=n.useCustomVisual(((Pe=m==null?void 0:m.customCardPreferences)==null?void 0:Pe.url)||""),g=y.useMemo(()=>{var ee;return(ee=f==null?void 0:f.visuals)==null?void 0:ee.find(xe=>{var Ee;return xe.name===((Ee=m==null?void 0:m.customCardPreferences)==null?void 0:Ee.componentName)})},[f,(Ve=m==null?void 0:m.customCardPreferences)==null?void 0:Ve.componentName]),p=n.resolveMultiInputType(m,g),h=y.useMemo(()=>n.getCustomVisualInputCards({frame:o,configCard:m,isMultiInputVisual:p==="multiple"}),[o,m,p]),N=y.useMemo(()=>{const ee=h.findIndex(xe=>(xe==null?void 0:xe.id)===(d==null?void 0:d.id));return ee<0?-1:n.getSlotIndexForCard(d,ee)},[h,d]),b=y.useMemo(()=>!m||p!=="multiple"||N<0?d.type:n.getEffectiveCardTypeForSlot(d,N,g==null?void 0:g.slots)??d.type,[m,p,N,d,g==null?void 0:g.slots]),v=y.useMemo(()=>b!==d.type?{...d,type:b}:d,[d,b]),k=y.useMemo(()=>u===0?null:Wr(d==null?void 0:d.sql),[d==null?void 0:d.sql,u]),P=y.useRef(!0),{setCardCustomCfg:C,setQueryResultColumns:S,setCardSql:A,setTempQueryData:I,setPythonStdOut:E,setCardPreferences:w,setCardType:D,setCardPython:M,setShowAIDialog:F,setCard:V,updateCardInFrame:R}=t.useEditorActions();t.useEditorStore(ee=>ee.onSave),t.useEditorStore(ee=>ee.onClose),t.useEditorStore(ee=>ee.actions.setSqlGen);const j=t.useEditorStore(ee=>ee.runSql),T=t.useEditorStore(ee=>ee.actions.setRunSql),L=t.useEditorStore(ee=>ee.actions.setIsSqlRunning),{data:O,isLoading:B,isFetching:z,isSuccess:_,isError:q,error:G,errorSql:H,queryKey:$,refetch:W,errorMessage:Q}=n.useEditorCardQuery(v),se=y.useRef($);se.current=$,y.useEffect(()=>{if(O)if(O.rowLimitExceeded&&n.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),E((O==null?void 0:O.output)||""),O.records.length>0){const{keys:ee}=n.getKeys(O.records);S(ee)}else S([])},[O,S,E]),y.useEffect(()=>{(B||z)&&(L(!0),S([])),(q||_)&&L(!1),q&&(S([]),E(""))},[B,z,O,E,q,_,L,S,G]),y.useEffect(()=>{j&&(s.getQueryData($)||W(),T(!1))},[j,W,T,$,s]);const ue=y.useRef(W);ue.current=W,y.useEffect(()=>{if(P.current){P.current=!1;return}ue.current()},[x]);function pe(ee,xe){A(ee),xe&&T(!0)}function ge(){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(qr,{})}),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:ee=>{ee.stopPropagation(),r(!1)},onPointerDown:ee=>ee.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(ae.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(Kr,{})})]})})]})]})}function ve(){return e.jsxs("div",{role:"editor-controls",className:"flex w-full flex-wrap items-center gap-2 px-4 pb-2 pt-3",children:[k&&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 ee;typeof navigator>"u"||!((ee=navigator.clipboard)!=null&&ee.writeText)||navigator.clipboard.writeText(k.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:k.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:B||z,onClick:()=>{Te.flushPendingEditorDrafts(),setTimeout(()=>{s.removeQueries({queryKey:se.current,exact:!0}),T(!0)},0)},className:"shrink-0",size:"xs",children:[B||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(Te.EditorClearButton,{}),e.jsxs(n.Toggle,{pressed:a,onPressedChange:ee=>r(ee),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(so,{currentSql:d==null?void 0:d.sql,currentPython:d==null?void 0:d.python,selectedDatabaseName:c,selectedSchemaName:i,selectedTableName:l,onApplySql:pe,onOpenFullAssistant:()=>F(!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:d.title,onSave:ee=>V({...d,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:d})]}),e.jsx(n.EditableText,{value:(d.description||"").trim(),onSave:ee=>V({...d,description:ee.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:ge()}),ve()]})}function ao(s,a){var c;let r=0,o=0;const d=Math.min(s.length,50);for(let i=0;i<d;i++){const l=(c=s[i])==null?void 0:c[a];if(!(l==null||l==="")){if(o++,typeof l=="number"||typeof l=="bigint")r++;else if(typeof l=="boolean")return"boolean"}}return o===0?"null":r/o>.7?"number":"text"}function ro(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 oo({data:s,card:a,paginationMetadata:r,onPaginationChange:o,onPageSizePreferenceChange:d,onSortChange:c,isLoading:i}){var w,D,M,F,V,R;const l=y.useMemo(()=>Object.keys(s[0]??{}),[s]),u=a.sql&&!((D=(w=a.preferences)==null?void 0:w.tablePrefs)!=null&&D.enableDevModePagination)?(F=(M=a.preferences)==null?void 0:M.tablePrefs)==null?void 0:F.pageSize:void 0,x=y.useMemo(()=>{var j;return n.sortByColumnsToSortState((j=a.config)==null?void 0:j.sortByColumns)},[(V=a.config)==null?void 0:V.sortByColumns]),{canSort:m,canUseLocalSorting:f,handlePaginationChange:g,handleSortChange:p,pagination:h,paginationMode:N,sorting:b}=n.useTableQueryState({card:a,dataLength:s.length,onPaginationChange:o,onSortChange:c,pageSize:u,paginationMetadata:r,sortState:x}),v=y.useMemo(()=>b.filter(j=>l.includes(j.id)),[b,l]),k=y.useMemo(()=>{const j={};for(const T of l)j[T]=ao(s,T);return j},[l,s]),P=y.useMemo(()=>l.map(j=>{const L=k[j]==="number";return{accessorKey:j,enableSorting:m,header:({column:O})=>{const B=O.getIsSorted();return e.jsxs("div",{className:t.cn("flex min-w-0 select-none items-center gap-1.5 transition-colors",O.getCanSort()&&"cursor-pointer hover:text-foreground",L&&"justify-end"),onClick:()=>O.getCanSort()&&O.toggleSorting(O.getIsSorted()==="asc"),children:[e.jsx("span",{className:"min-w-0 truncate",title:j,children:j}),B==="asc"?e.jsx(n.ArrowUpIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):B==="desc"?e.jsx(n.ArrowDownIcon,{className:"h-3.5 w-3.5 shrink-0 text-foreground"}):O.getCanSort()?e.jsx(n.ChevronsUpDown,{className:"h-3 w-3 shrink-0 opacity-0 transition-opacity group-hover/header:opacity-50"}):null]})},cell:({getValue:O})=>{const B=O(),z=B===null;return e.jsx("div",{className:t.cn("overflow-hidden truncate whitespace-nowrap leading-5",L&&"text-right tabular-nums",z&&"text-muted-foreground/50 italic"),children:ro(B)})}}}),[m,k,l]),C=Math.max(P.length,1),S=n.useReactTable({data:s,columns:P,getCoreRowModel:n.getCoreRowModel(),getPaginationRowModel:N==="client"?n.getPaginationRowModel():void 0,onSortingChange:p,getSortedRowModel:f?n.getSortedRowModel():void 0,onPaginationChange:N==="disabled"?void 0:g,manualPagination:N==="server"||N==="disabled",manualSorting:!f,pageCount:N==="server"&&r?r.pageCount:void 0,state:{sorting:v,pagination:h}}),A=N==="server"&&r?r.totalCount:s.length,I=N!=="disabled"&&(N==="server"||A>10),E=l.length>0?`${l.length*144}px`:"100%";return e.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-col",children:[i&&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:"relative min-h-0 w-full grow overflow-auto rounded-none border-0 bg-transparent text-foreground",children:[e.jsxs("table",{className:"w-full text-sm [border-spacing:0]",style:{minWidth:E},children:[e.jsx(n.TableHeader,{className:"sticky top-0 z-10 bg-muted [&_tr]:border-b-0",children:S.getHeaderGroups().map(j=>e.jsx(n.TableRow,{className:"border-b-0 hover:bg-transparent",children:j.headers.map(T=>{const O=k[T.id]==="number";return e.jsx(n.TableHead,{className:t.cn("group/header relative h-auto border-b border-transparent bg-muted/95 px-4 py-2 align-middle text-[10px] font-medium tracking-[0.08em] text-muted-foreground after:absolute after:bottom-0 after:left-0 after:right-0 after:h-px after:bg-border/60",O&&"text-right"),children:T.isPlaceholder?null:n.flexRender(T.column.columnDef.header,T.getContext())},T.id)})},j.id))}),e.jsx(n.TableBody,{children:(R=S.getRowModel().rows)!=null&&R.length?S.getRowModel().rows.map(j=>e.jsx(n.TableRow,{className:"border-b border-border/40 transition-colors","data-state":j.getIsSelected()&&"selected",children:j.getVisibleCells().map(T=>{const O=k[T.column.id]==="number";return e.jsx(n.TableCell,{className:t.cn("overflow-hidden px-4 py-2 text-[13px] text-foreground/90",O&&"text-right"),children:n.flexRender(T.column.columnDef.cell,T.getContext())},T.id)})},j.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:C,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]}),e.jsx("div",{className:"shrink-0 border-t border-border/60 bg-background text-[13px]",children:I?e.jsx(n.DataTablePagination,{totalColumns:l.length,pageCount:N==="server"&&r?r.pageCount:S.getPageCount(),pageIndex:S.getState().pagination.pageIndex,pageSize:S.getState().pagination.pageSize,rowCount:A,selectedRowCount:0,setPageIndex:S.setPageIndex,setPageSize:S.setPageSize,canPreviousPage:N==="server"&&r?r.hasPrevPage:S.getCanPreviousPage(),canNextPage:N==="server"&&r?r.hasNextPage:S.getCanNextPage(),previousPage:S.previousPage,nextPage:S.nextPage,onPageSizePreferenceChange:d,onClearSelection:()=>{},paginationMode:N,showExport:!1}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[A.toLocaleString()," ",A===1?"row":"rows"," · ",l.length," ",l.length===1?"column":"columns"]}),v.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Sorted by"," ",e.jsx("span",{className:"font-medium text-foreground/70",children:v[0].id})," ",v[0].desc?"↓":"↑"]})]})})]})}const _n=[{value:"table",label:"Table"},{value:"aggregateTable",label:"Aggregate"},{value:"pivotTable",label:"Pivot"},{value:"detailTable",label:"Detail"}];function lo({className:s}){const a=t.useEditorStore(p=>p.card),r=t.useEditorStore(p=>p.frame),o=t.useEditorStore(p=>p.editorContext),d=Te.useEffectiveEditorCardType(),{setCard:c,updateCardInFrame:i}=t.useEditorActions(),l=(o==null?void 0:o.type)==="documentSection"?_n.filter(p=>["table","pivotTable"].includes(p.value)):_n,u=["table","aggregateTable","pivotTable","detailTable"].includes(d),x=At.hasValidCardConfig(a.config),m=n.isCustomVisualConfigCard(a,r.cards);if(!u||!x||m)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 f=p=>{if(p===d||m)return;const h=p,N=a.config??{},b=g(d,h,N),v={...a,type:h,config:b};c(v),i(v)},g=(p,h,N)=>{var v;if(p===h)return N;if(h==="detailTable"){const k=A=>A==null?void 0:A.toLowerCase().replace(/\s+/g,"").trim(),P=(A,I)=>{const E=[k(A.label),k(A.qualifiedFieldName),k(A.name)].filter(Boolean),w=[k(I.label),k(I.qualifiedFieldName),k(I.name)].filter(Boolean);return E.some(D=>w.includes(D))},C=(N.groupByColumns||[]).map(A=>({...A,role:"detail"})),S=((v=N.sortByColumns)==null?void 0:v.filter(A=>C.some(I=>P(A,I))))??[];return{...N,detailTableBackup:{groupByColumns:N.groupByColumns,metricColumns:N.metricColumns,pivotByColumns:N.pivotByColumns,sortByColumns:N.sortByColumns,rowAggregates:N.rowAggregates,columnAggregates:N.columnAggregates},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:S,rowAggregates:[],columnAggregates:[]}}let b=N;if(p==="detailTable")if(N.detailTableBackup)b={...N,...N.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const k=(N.detailColumns||[]).map(P=>({...P,role:"groupby"}));b={...N,groupByColumns:k,detailColumns:[]}}return h==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{role:"tablist",className:t.cn("flex items-center gap-5",s),children:l.map(p=>{const h=d===p.value;return e.jsx("button",{type:"button",role:"tab","aria-selected":h,onClick:()=>f(p.value),className:t.cn("-mb-px flex h-9 items-center border-b-2 text-[12px] transition-colors",h?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:p.label},p.value)})})}function io({text:s,children:a,className:r,copiedLabel:o="Copied",disabled:d,onClick:c,onCopy:i,...l}){const[u,x]=y.useState(!1);return e.jsxs("button",{type:"button",className:t.cn("group/copy-on-click relative block w-full text-left transition-colors","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",d&&"cursor-default opacity-60",r),disabled:d,onClick:async m=>{if(c==null||c(m),!m.defaultPrevented)try{let f=!1;if(i)f=await i();else if(typeof s=="string"){if(typeof navigator>"u"||!navigator.clipboard)return;await navigator.clipboard.writeText(s),f=!0}if(!f)return;x(!0),setTimeout(()=>x(!1),1200)}catch(f){console.error("Failed to copy text",f)}},...l,children:[a,e.jsx("span",{"aria-live":"polite",className:t.cn("pointer-events-none absolute right-3 top-2.5 text-[10px] font-medium text-muted-foreground transition-opacity",u?"opacity-100":"opacity-0"),children:o})]})}const zn={async writeTextToClipboard(s){return typeof navigator>"u"||!navigator.clipboard?!1:(await navigator.clipboard.writeText(s),!0)}},ns=50;function co(s){return`Copy ${s}`}const uo=[{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"}];function qn(s){try{return JSON.stringify(s,null,2)}catch(a){return console.error("Unable to stringify debug payload",a),null}}function kt(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";case"columns":return"Columns";case"dashboardFilters":return"Dashboard filters";default:return"Payload"}}function mo(s){if(!s||typeof s!="object")return{value:s};const a=s.records;return!Array.isArray(a)||a.length<=ns?{value:s}:{value:{...s,records:a.slice(0,ns),previewMeta:{truncatedRecords:!0,displayedRecords:ns,totalRecords:a.length}},truncationMessage:`Preview showing first ${ns} records of ${a.length}. Copy actions include full payload.`}}function ca({isOpen:s,onClick:a}){return e.jsxs(t.Button,{onClick:a,variant:"outline",size:"xs","aria-expanded":s,children:[e.jsx(t.Info,{className:"mr-1.5 h-3 w-3"}),s?"Hide details":"Show details"]})}function da({debugPayloads:s,className:a}){const[r,o]=y.useState(null),d=t.useEditorStore(P=>P.card),c=t.useEditorStore(P=>P.frame),i=t.useDashboardStore(P=>P.selectedSheetId),l=t.useDashboardStore(P=>{var C;return(C=P.dashboard)==null?void 0:C.id}),u=y.useMemo(()=>({cardId:d.id||null,frameId:c.id||null,sheetId:i||null,dashboardId:l||null}),[d.id,c.id,i,l]),x=y.useMemo(()=>({queryRequest:s==null?void 0:s.queryRequest,queryResponse:s==null?void 0:s.queryResponse,cardConfig:d.config,dataSource:d.dataSource,columns:s==null?void 0:s.columns,dashboardFilters:s==null?void 0:s.dashboardFilters,cardMetadata:u}),[s==null?void 0:s.queryRequest,s==null?void 0:s.queryResponse,s==null?void 0:s.columns,s==null?void 0:s.dashboardFilters,d.config,d.dataSource,u]),m=!!s,f=y.useMemo(()=>[{label:"Card ID",value:d.id||""},{label:"Frame ID",value:c.id||""},{label:"Sheet ID",value:i||""},{label:"Dashboard ID",value:l||""}],[d.id,c.id,i,l]),g=P=>x[P]!==void 0,p=y.useMemo(()=>{if(!r)return null;const P=x[r];if(P===void 0)return null;const C=r==="queryResponse"?mo(P):{value:P},S=qn(C.value);return S?{target:r,title:kt(r),json:S,truncationMessage:C.truncationMessage}:null},[r,x]),h=p?p.title:"Inspect payload",N=async P=>{const C=x[P];if(C===void 0)return n.ue.error(`No ${kt(P).toLowerCase()} available`),!1;const S=qn(C);if(!S)return n.ue.error(`Unable to serialize ${kt(P).toLowerCase()}`),!1;try{return await zn.writeTextToClipboard(S)?(n.ue.success(`${kt(P)} copied`),!0):(n.ue.error("Clipboard is not available"),!1)}catch(A){return console.error("Failed to copy debug payload",A),n.ue.error(`Unable to copy ${kt(P).toLowerCase()}`),!1}},b=async()=>p?N(p.target):!1,v=async P=>{if(!P.value)return!1;try{return await zn.writeTextToClipboard(P.value)?!0:(n.ue.error("Clipboard is not available"),!1)}catch(C){return console.error("Failed to copy card detail",C),n.ue.error(`Unable to copy ${P.label}`),!1}},k=P=>{if(x[P]===void 0){n.ue.error(`No ${kt(P).toLowerCase()} available`);return}o(P)};return e.jsxs("div",{className:t.cn("mb-3 overflow-hidden rounded-[6px] border border-border/60 bg-card",a),children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2",children:f.map((P,C)=>e.jsxs(io,{text:P.value,"aria-label":co(P.label),title:P.value?`${P.value} - click to copy`:"N/A",disabled:!P.value,onCopy:()=>v(P),className:t.cn("min-w-0 border-border/60 px-3 py-2.5 hover:bg-muted/30",C!==f.length-1&&"border-b",C>=2&&"md:border-b-0",C%2===0&&"md:border-r"),children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:P.label}),e.jsx("code",{className:"mt-1 block truncate pr-12 font-mono text-[12px] leading-5 text-foreground",children:P.value||"N/A"})]},P.label))}),m&&e.jsxs("div",{className:"border-t border-border/60",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Diagnostics"}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7",children:[e.jsx(Ue.Eye,{className:"mr-1.5 h-3.5 w-3.5"}),h,e.jsx(ae.ChevronDown,{className:"ml-1 h-3.5 w-3.5"})]})}),e.jsx(n.DropdownMenuContent,{align:"end",className:"w-48 p-1",children:uo.map(P=>e.jsx(n.DropdownMenuItem,{disabled:!g(P.target),onSelect:()=>k(P.target),className:t.cn("h-7 rounded-control px-2 text-[12px] font-normal leading-4",r===P.target&&"bg-accent"),children:P.label},`preview-${P.target}`))})]})]}),p&&e.jsxs("div",{className:"space-y-2 border-t border-border/60 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"truncate text-[12px] font-medium text-foreground",children:p.title}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(n.CopyButton,{text:p.json,className:"h-6 w-6 rounded-control px-0 text-muted-foreground",ariaLabel:"Copy diagnostics payload",onCopy:b}),e.jsx(t.Button,{variant:"ghost",size:"xs",className:"h-6 px-2 text-[11px]",onClick:()=>o(null),children:"Close"})]})]}),p.truncationMessage&&e.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:p.truncationMessage}),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:p.json,language:"json"})})]})]})]})}const $n="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline";function os({error:s,errorSql:a,errorTitle:r="Unable to load data",onOpenInEditor:o,onDebugWithAssistant:d,onSendFeedback:c,showFeedbackButton:i=!0,showCardDetails:l=!1,debugPayloads:u,className:x}){const[m,f]=y.useState(!1),[g,p]=y.useState(!1),b=!!d||!!(o&&a);return e.jsxs("div",{className:t.cn("w-full space-y-3 rounded-[6px] border border-border/60 bg-card p-4",x),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})]}),l&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:e.jsx(ca,{isOpen:g,onClick:()=>p(v=>!v)})}),l&&g&&e.jsx(da,{debugPayloads:u,className:"mb-0"}),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})})]}),b&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[d&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:d,children:[e.jsx(ir,{className:"h-3.5 w-3.5"}),"Debug with Assistant"]}),o&&a&&e.jsxs(t.Button,{variant:"outline",size:"xs",onClick:o,children:[e.jsx(sa,{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:()=>f(v=>!v),className:$n,children:m?"Hide query details":"Show query details"}),i&&c&&e.jsx("button",{type:"button",onClick:c,className:$n,children:"Report this issue"})]}),a&&e.jsx(n.Collapsible,{open:m,onOpenChange:f,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 Ls(s,a){const r=t.useEditorStore(x=>x.card),o=t.useEditorStore(x=>x.isDevMode),{switchEditorMode:d,setRunSql:c,runAssistant:i}=t.useEditorActions();return{isDevMode:o,handleOpenInEditor:o?void 0:()=>{const x=a||r.sql||r.python||"";d("dev",{sqlToLoad:x}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:o?()=>{const x=`Can you help me debug this query?
172
+
173
+ Error:
174
+
175
+ ${s}
176
+
177
+ Error SQL:
178
+
179
+ ${a||r.sql||r.python}
180
+
181
+ `;i(x)}:void 0}}function ua({className:s,style:a,...r}){var de,Le,Me,Qe,re,je,Ce;const o=t.useEditorStore(ne=>ne.card),d=n.useDashboardAppearance(),i=t.useEditorStore(ne=>ne.isDevMode)?!1:((de=o.customCardPreferences)==null?void 0:de.showCardHeader)??!0,l=((Me=(Le=o.preferences)==null?void 0:Le.displayOptions)==null?void 0:Me.showInlineFilterBar)??!0,u=t.useEditorStore(ne=>ne.frame),x=t.useEditorStore(ne=>ne.inlineFilterValuesMap[o.id]),m=t.useDashboardStore(ne=>ne.dashboard.filters),f=t.useDashboardStore(ne=>ne.selectedSheetId),[g,p]=y.useState(!1),{currentUser:h}=n.useCurrentUserInfo(),{tokenProps:N}=y.useContext(n.SemaphorContext),b=t.useEditorStore(ne=>ne.actions.setRunSql),v=t.useEditorStore(ne=>ne.actions.setCardInlineFilterValue),k=t.useEditorStore(ne=>ne.actions.removeCardInlineFilterValue),{updateFilter:P}=t.useDashboardActions(),C=m==null?void 0:m.find(ne=>ne.id===u.filterId),S=y.useMemo(()=>n.findCustomVisualConfigCard(u,o),[u,o]),{manifest:A}=n.useCustomVisual(((Qe=S==null?void 0:S.customCardPreferences)==null?void 0:Qe.url)||""),I=y.useMemo(()=>{var ne;return(ne=A==null?void 0:A.visuals)==null?void 0:ne.find(Ie=>{var ke;return Ie.name===((ke=S==null?void 0:S.customCardPreferences)==null?void 0:ke.componentName)})},[A,(re=S==null?void 0:S.customCardPreferences)==null?void 0:re.componentName]),E=n.resolveMultiInputType(S,I),w=y.useMemo(()=>n.getCustomVisualInputCards({frame:u,configCard:S,isMultiInputVisual:E==="multiple"}),[u,S,E]),D=y.useMemo(()=>{const ne=w.findIndex(Ie=>(Ie==null?void 0:Ie.id)===(o==null?void 0:o.id));return ne<0?-1:n.getSlotIndexForCard(o,ne)},[w,o]),M=y.useMemo(()=>!S||E!=="multiple"||D<0?o.type:n.getEffectiveCardTypeForSlot(o,D,I==null?void 0:I.slots)??o.type,[S,E,D,o,I==null?void 0:I.slots]),F=M??o.type,V=y.useMemo(()=>F===o.type?o:{...o,type:F},[o,F]),R=V.type==="table"||V.type==="matrixTable"||V.type==="pivotTable"||V.type==="aggregateTable"||V.type==="detailTable",j=y.useMemo(()=>M!==o.type?{...o,type:M}:o,[o,M]),{data:T,isLoading:L,isFetching:O,errorMessage:B,errorSql:z,pagination:_}=n.useEditorCardQuery(j),q=F==="matrixTable"&&n.hasMatrixResultData(T),G=n.getMatrixVisualLoadingState({data:T,isLoading:L,isFetching:O}),{handleOpenInEditor:H,handleDebugWithAssistant:$}=Ls(B,z||o.sql||o.python),W=y.useMemo(()=>(T==null?void 0:T.records)||[],[T==null?void 0:T.records]),{setCard:Q,updateCardInFrame:se}=t.useEditorActions(),{data:ue}=n.useTopoJson(V),pe=V.id,ge=V.config,ve=V.interactionConfig,Pe=V.customCfg,Ve=V.preferences,ee=V.queryConfig,xe=!!V.sql,Ee=T==null?void 0:T.records,qe=y.useMemo(()=>({id:pe,type:F,config:ge,interactionConfig:ve,sql:xe?"__editor_sql__":""}),[pe,F,ge,ve,xe]),$e=y.useMemo(()=>{var ne;return F!=="pivotTable"||!((ne=T==null?void 0:T.records)!=null&&ne.length)?null:{records:T.records,columnSubtotalMeta:T.columnSubtotalMeta,subtotalColumns:T.subtotalColumns||[],pivotSchema:T.pivotSchema||[],groupByColumns:T.groupByColumns}},[F,T==null?void 0:T.records,T==null?void 0:T.columnSubtotalMeta,T==null?void 0:T.subtotalColumns,T==null?void 0:T.pivotSchema,T==null?void 0:T.groupByColumns]),ce=n.usePivotTableConfig(V,$e,(je=T==null?void 0:T.metadata)==null?void 0:je.comparisonMetadata),Re=()=>{p(!0)},we=y.useMemo(()=>{const ne=typeof window<"u"?window.location.href:"",Ie=typeof navigator<"u"?navigator.userAgent:"",ke=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:h,tokenContext:N,systemState:{cardConfig:o.config,dataSource:o.dataSource,dashboardFilters:m,errorMessage:B||void 0,errorSql:z||o.sql||o.python,generatedSql:z||o.sql},metadata:{url:ne,userAgent:Ie,timestamp:new Date().toISOString(),viewport:ke}}},[h,N,o,m,B,z]),ie=(ne,Ie)=>{var Be,We;const ke={...o,paginationConfig:{page:ne+1,pageSize:Ie}};Q(ke),se(ke),o.sql&&((We=(Be=o.preferences)==null?void 0:Be.tablePrefs)!=null&&We.enableDevModePagination)&&b(!0)},K=ne=>{var Be,We,Se,De,et;const Ie=n.sortStateToSortByColumns(ne,(Be=o.config)==null?void 0:Be.metricColumns,(We=o.config)==null?void 0:We.groupByColumns,(Se=o.config)==null?void 0:Se.detailColumns),ke={...o,config:{...o.config||{},sortByColumns:Ie}};Q(ke),se(ke),o.sql&&((et=(De=o.preferences)==null?void 0:De.tablePrefs)!=null&&et.enableDevModePagination)&&b(!0)},le=y.useMemo(()=>{var ne;return!pe||!Ee?null:n.createChartConfig({card:qe,data:Ee,cardType:F,queryConfig:ee,customCfg:Pe,preferences:Ve,topoJson:ue,comparisonMetadata:(ne=T==null?void 0:T.metadata)==null?void 0:ne.comparisonMetadata})},[qe,pe,Pe,Ve,ee,Ee,(Ce=T==null?void 0:T.metadata)==null?void 0:Ce.comparisonMetadata,F,ue]);function me(ne){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:ne})})}function te(){var ne;if(T!=null&&T.records&&(T==null?void 0:T.records.length)===0&&!L&&!O&&!q)return B?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(os,{error:B,errorSql:z||o.sql||o.python,onOpenInEditor:H,onDebugWithAssistant:$,onSendFeedback:Re,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((L||O)&&(!(T!=null&&T.records)||T.records.length===0)&&!q)return F==="table"||F==="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(!V.id)return null;if(F==="custom")return me(o);if(!["table","matrixTable","pivotTable","aggregateTable","detailTable","custom"].includes(F)&&le)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:L||O?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:le})});if(F==="table"||F==="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:V,data:W,totalsByColumnId:T==null?void 0:T.tableTotalsByColumnId,comparisonMetadata:(ne=T==null?void 0:T.metadata)==null?void 0:ne.comparisonMetadata,paginationMetadata:_,onPaginationChange:ie,onSortChange:K,isLoading:L||O})});if(F==="matrixTable")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.MatrixTableVisual,{result:T==null?void 0:T.matrixResult,isLoading:G})});if(F==="pivotTable"&&ce)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:V,data:ce.data,options:ce.options,onAggregationChange:Ie=>{const ke=n.handleAggregationChange(Ie,o.config),Be={...o,config:ke};Q(Be),se(Be)},onAggregationLabelChange:Ie=>{const ke=n.handleAggregationLabelChange(Ie,o.config),Be={...o,config:ke};Q(Be),se(Be)}})});if(F==="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:V,data:(T==null?void 0:T.records)||[],groupByColumns:T==null?void 0:T.groupByColumns,pivotSchema:T==null?void 0:T.pivotSchema,paginationMetadata:_,onPaginationChange:ie,onAggregationChange:Ie=>{const ke=n.handleAggregationChange(Ie,o.config),Be={...o,config:ke};Q(Be),se(Be)},isLoading:L||O})})}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:{...d.cardFrameStyle,...a},...r,children:[(L||O)&&(T==null?void 0:T.records)&&T.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"})}),i&&e.jsxs(n.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:d.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:o.title,onSave:ne=>Q({...o,title:ne}),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:o}),e.jsx(Te.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(lo,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(o.description||"").trim(),onSave:ne=>Q({...o,description:ne.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:C.title||C.column,onSave:ne=>P({...C,title:ne}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:C})]})]}),l&&o.inlineFilters&&o.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:d.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:o,sheetId:f||"",inlineFilterValues:x,setInlineFilterValue:ne=>v(o.id,ne),removeInlineFilterValue:ne=>k(o.id,ne)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col",R?"p-0 [&_.data-table-scroll-container]:border-0 [&_.data-table-scroll-container]:bg-transparent":"px-4"),style:R?void 0:d.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:te()}),n.isCardSummaryVisibleOnCard(V)&&e.jsx("div",{className:t.cn("pt-3",R&&"px-4"),children:e.jsx(n.CardSummary,{card:V,mode:"editor"})})]}),e.jsx(n.FeedbackDialog,{open:g,onOpenChange:p,feedbackData:we,showDebugInfo:!0})]})}const js=({language:s,value:a,onChange:r,readonly:o})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:o,embedded:!0}),xo=()=>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."})]})]}),ho=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:o,onCodeChange:d})=>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(js,{language:"json",value:r,onChange:o})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(js,{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(js,{language:"javascript",value:s,onChange:d})})]}),po=({error:s,hasCardCustomConfig:a,onReset:r,onApply:o,onClose:d})=>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:o,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:d,variant:"outline",children:"Close"})]});function fo({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[o,d]=y.useState(!1),[c,i]=y.useState(""),[l,u]=y.useState(""),[x,m]=y.useState(""),[f,g]=y.useState(""),p=t.useEditorStore(D=>D.card),h=Te.useEffectiveEditorCardType(),N=t.useEditorStore(D=>D.card.customCfg),b=N?JSON.stringify(N,null,2):"",v=y.useMemo(()=>h!==p.type?{...p,type:h}:p,[p,h]),{data:k}=n.useEditorCardQuery(v),{data:P}=n.useTopoJson(p),{setCardCustomCfg:C,setCustomVisualCode:S}=t.useEditorActions(),A=D=>{var M,F;return JSON.stringify({...D,data:{...D.data,datasets:(F=(M=D.data)==null?void 0:M.datasets)==null?void 0:F.map(V=>({...V,data:[]}))}},null,2)},I=()=>{var M,F,V;if(!((M=k==null?void 0:k.records)!=null&&M.length))return;const D=n.createChartConfig({card:p,data:k.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:P,comparisonMetadata:(F=k==null?void 0:k.metadata)==null?void 0:F.comparisonMetadata});if(D){i(A(D)),m(((V=p.preferences)==null?void 0:V.customVisualCode)||"");const R=n.merge(D,N);u(A(R))}},E=()=>{try{if(x&&S(x),l){const D=JSON.parse(l),M=n.getObjectDiff(JSON.parse(c),D);C(M),g("")}}catch{g("Invalid JSON configuration")}},w=Object.keys(N||{}).length===0;return e.jsxs(n.Dialog,{open:o,onOpenChange:d,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:I,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",w?"":"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:I,className:t.cn(w?"":"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(xo,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(ua,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ho,{customCode:x,cardCustomCfgString:b,mergedConfig:l,onConfigChange:D=>u(D??""),onCodeChange:D=>m(D??"")})]}),e.jsx(po,{error:f,hasCardCustomConfig:!!N,onReset:()=>{u(c),C(null)},onApply:E,onClose:()=>d(!1)})]})]})}function go(s){let a=0;for(let o=0;o<s.length;o++)a=s.charCodeAt(o)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function bo(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function Ms({chartType:s,chartName:a,isCustom:r=!1,className:o="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,o);const d=n.getAutoDetectedChartIcon(a);if(d)return y.cloneElement(d,{className:o});const c=bo(a),i=go(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",o),style:{backgroundColor:i},children:c})}function jo({isStarred:s,onClick:a,className:r}){const o=d=>{d.stopPropagation(),d.preventDefault(),a(d)};return e.jsx("button",{type:"button",onClick:o,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 Kn({chartType:s,chartName:a,isCustom:r=!1,pluginName:o,isStarred:d,showStar:c=!0,isSelected:i=!1,onSelect:l,onToggleStar:u}){return e.jsxs("div",{className:"group relative",children:[c&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",d?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(jo,{isStarred:d,onClick:()=>u()})}),r&&o&&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:o})]})}),e.jsxs("button",{type:"button",onClick:l,"aria-pressed":i,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",i&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(Ms,{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})]})]})}function ma(s,a){return s==="matrixTable"?!a.isDevMode:!0}function Kt(s,a){return s==="matrixTable"?!1:ma(s,a)}const vo=[{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"},{id:"matrixTable",name:"Matrix Table"}];function yo(s){return vo.filter(a=>ma(a.id,s))}function xa({onChartSelect:s,onClose:a}){const[r,o]=y.useState(""),{starredCharts:d,isStarred:c,toggleStar:i}=n.useStarredChartsStore(),{data:l=[],isLoading:u}=n.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:m,setIsDevMode:f}=t.useEditorStore(M=>M.actions),g=t.useEditorStore(M=>M.card),p=t.useEditorStore(M=>M.isDevMode),{setCardCustomCfg:h,setCustomCardPreferences:N,setVisualizationMode:b,setQueryConfig:v,replaceFrameCards:k,clearModeDrafts:P,initializeModeDrafts:C}=t.useEditorActions(),S=y.useMemo(()=>{const M=yo({isDevMode:p});if(!r)return M;const F=r.toLowerCase();return M.filter(V=>V.name.toLowerCase().includes(F))},[p,r]),A=y.useMemo(()=>{const M=l.filter(V=>V.componentType==="chart"&&V.pluginType!=="standard");if(!r)return M;const F=r.toLowerCase();return M.filter(V=>V.name.toLowerCase().includes(F))},[l,r]),I=M=>{h(null),m({}),b("builtin"),x(M),["custom","text","map"].includes(M)&&(f(!0),v(void 0)),s==null||s(M),a==null||a()},E=M=>{h(null),m({}),b("builtin"),v(void 0);const F=n.resolveMultiInputTypeFromVisual(M);if(F==="multiple"&&M.slots&&M.slots.length>0){P();const R=n.createCardsFromSlots(M.slots,M,g);k(R),R[0]&&C(R[0]),a==null||a();return}else x("custom"),N({type:"component",visualType:F,url:M.url,componentName:M.name,icon:M.icon,pluginChartType:M.chartType,minInputs:M.minInputs,maxInputs:M.maxInputs});s==null||s("custom",M),a==null||a()},w=M=>{const F={type:"default",id:M.id,name:M.name};i(F)},D=M=>{const F={type:"custom",id:M.name,url:M.url,icon:M.icon,name:M.name};i(F)};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(Ue.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:M=>o(M.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(M=>e.jsx(Kn,{chartType:M.id,chartName:M.name,isCustom:!1,isStarred:c("default",M.id),onSelect:()=>I(M.id),onToggleStar:()=>w(M)},M.id))}),A.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:A.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:A.map((M,F)=>e.jsx(Kn,{chartName:M.name,isCustom:!0,pluginName:M.pluginName,isStarred:c("custom",M.name),onSelect:()=>E(M),onToggleStar:()=>D(M)},`${M.url}-${M.name}-${F}`))})]}),u&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),S.length===0&&A.length===0&&!u&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function No({selectedChart:s,onChartChange:a}){var A,I,E,w;const r=t.useEditorStore(D=>D.card),o=t.useEditorStore(D=>D.frame),d=t.useEditorStore(D=>D.isDevMode),{replaceFrameCards:c,clearModeDrafts:i,initializeModeDrafts:l,setIsDevMode:u}=t.useEditorActions(),x=y.useMemo(()=>n.findCustomVisualConfigCard(o,r),[o,r]),{manifest:m}=n.useCustomVisual(((A=x==null?void 0:x.customCardPreferences)==null?void 0:A.url)||""),f=y.useMemo(()=>{var D;return(D=m==null?void 0:m.visuals)==null?void 0:D.find(M=>{var F;return M.name===((F=x==null?void 0:x.customCardPreferences)==null?void 0:F.componentName)})},[m,(I=x==null?void 0:x.customCardPreferences)==null?void 0:I.componentName]),g=n.resolveMultiInputType(x,f)==="multiple",p=Te.useEffectiveEditorCardType(),h=g?p:s??r.type,N=(E=r==null?void 0:r.customCardPreferences)==null?void 0:E.componentName,b=(w=x==null?void 0:x.customCardPreferences)==null?void 0:w.componentName,v=g&&!!b,k=y.useMemo(()=>{const D=n.chartTypes.find(M=>M.id===h);return D?D.label:h==="custom"?N||"Custom Visual":"Select chart type"},[h,N]),P=y.useMemo(()=>{const D=n.chartTypes.find(M=>M.id===h);if(D){const M=D.icon;return e.jsx(M,{className:"h-4 w-4"})}if(h==="custom"&&N){const M=n.getAutoDetectedChartIcon(N);return M||e.jsx(Ms,{chartName:N,isCustom:!0,className:"h-4 w-4"})}return e.jsx(fr,{className:"h-4 w-4"})},[h,N]);return{displayChartType:h,displayLabel:k,displayIcon:P,showBadge:v,badgeLabel:b,isMultiInputContext:g,handleChartSelect:D=>{a==null||a(D)},handleClearCustomVisual:D=>{D.stopPropagation();const M={...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([M]),i(),l(M),d&&u(!0),a==null||a("bar")}}}function Co({selectedChart:s,onChartChange:a,variant:r="ghost",className:o}){const[d,c]=y.useState(!1),{displayLabel:i,displayIcon:l,showBadge:u,badgeLabel:x,handleChartSelect:m,handleClearCustomVisual:f}=No({selectedChart:s,onChartChange:a}),g=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",o),children:[e.jsxs(t.Popover,{open:d,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:g?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":d,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:[l,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:i})]}),e.jsx(ae.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",d&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":d,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:[l,e.jsx("span",{className:"truncate",children:i})]}),e.jsx(ae.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:p=>p.preventDefault(),children:e.jsx(xa,{onChartSelect:p=>m(p),onClose:()=>c(!1)})})]}),u&&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:f,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(ae.X,{className:"h-2.5 w-2.5"})})]})]})}const Dt={table:t.Table2,matrixTable:n.Grid3x3,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},Ut={table:"Table",matrixTable:"Matrix 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"},ha=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],pa=6;function So({selectedChart:s,onChartChange:a}){var P,C;const[r,o]=y.useState(!1),d=t.useEditorStore(S=>S.card),{setCardType:c,setCardPreferences:i}=t.useEditorStore(S=>S.actions),{setCardCustomCfg:l,setCustomCardPreferences:u,setQueryConfig:x,replaceFrameCards:m,clearModeDrafts:f,initializeModeDrafts:g}=t.useEditorActions(),{starredCharts:p}=n.useStarredChartsStore(),{data:h=[]}=n.useCustomVisualsQuery(),N=t.useEditorStore(S=>S.isDevMode),b=y.useMemo(()=>{const S=p.filter(w=>w.type==="default"?Kt(w.id,{isDevMode:N}):h.some(D=>D.name===w.id)),A=new Set(S.map(w=>w.id)),I=ha.filter(w=>!A.has(w.id)&&Kt(w.id,{isDevMode:N}));return[...S.map(w=>({id:w.id,label:w.name,icon:w.type==="default"?Dt[w.id]:void 0,isCustom:w.type==="custom",url:w.url})),...I.map(w=>({id:w.id,label:Ut[w.id]??w.id,icon:Dt[w.id],isCustom:!1}))].slice(0,pa)},[p,h,N]),v=s==="custom"&&((P=d==null?void 0:d.customCardPreferences)==null?void 0:P.componentName);return b.some(S=>{var A;return S.isCustom?v&&((A=d==null?void 0:d.customCardPreferences)==null?void 0:A.componentName)===S.id:s===S.id})||(s==="custom"?(C=d==null?void 0:d.customCardPreferences)!=null&&C.componentName:Ut[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(fa,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function fa({selectedChart:s,onChartChange:a,compactMore:r=!1}){var I,E;const[o,d]=y.useState(!1),c=t.useEditorStore(w=>w.card),{setCardType:i,setCardPreferences:l}=t.useEditorStore(w=>w.actions),{setCardCustomCfg:u,setCustomCardPreferences:x,setQueryConfig:m,replaceFrameCards:f,clearModeDrafts:g,initializeModeDrafts:p}=t.useEditorActions(),{starredCharts:h}=n.useStarredChartsStore(),{data:N=[]}=n.useCustomVisualsQuery(),b=t.useEditorStore(w=>w.isDevMode),v=((I=c==null?void 0:c.customCardPreferences)==null?void 0:I.componentName)??null,k=y.useMemo(()=>{const w=h.filter(R=>R.type==="default"?Kt(R.id,{isDevMode:b}):N.some(j=>j.name===R.id)),D=new Set(w.map(R=>R.id)),M=ha.filter(R=>!D.has(R.id)&&Kt(R.id,{isDevMode:b})),F=[...w.map(R=>({id:R.id,label:R.name,icon:R.type==="default"?Dt[R.id]:void 0,isCustom:R.type==="custom",url:R.url})),...M.map(R=>({id:R.id,label:Ut[R.id]??R.id,icon:Dt[R.id],isCustom:!1}))];if(!F.some(R=>R.isCustom?s==="custom"&&R.id===v:R.id===s))if(s==="custom"&&v){const R=N.find(j=>j.name===v);R&&F.unshift({id:R.name,label:R.name,icon:void 0,isCustom:!0,url:R.url})}else s&&Dt[s]&&Kt(s,{isDevMode:b})&&F.unshift({id:s,label:Ut[s]??s,icon:Dt[s],isCustom:!1});return F.slice(0,pa)},[h,N,s,v,b]),P=s==="custom"&&v,C=w=>{if(w.isCustom){const D=N.find(V=>V.name===w.id);if(!D)return;u(null),l({}),m(void 0);const M=n.resolveMultiInputTypeFromVisual(D);if(M==="multiple"&&D.slots&&D.slots.length>0){g();const V=n.createCardsFromSlots(D.slots,D,c);f(V),V[0]&&p(V[0]);return}i("custom"),x({type:"component",visualType:M,url:D.url,componentName:D.name,icon:D.icon,pluginChartType:D.chartType,minInputs:D.minInputs,maxInputs:D.maxInputs}),a("custom");return}a(w.id)},S=k.some(w=>{var D;return w.isCustom?P&&((D=c==null?void 0:c.customCardPreferences)==null?void 0:D.componentName)===w.id:s===w.id}),A=S?"More":s==="custom"?((E=c==null?void 0:c.customCardPreferences)==null?void 0:E.componentName)||"Custom":Ut[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:k.map(w=>{var F;const D=w.icon,M=w.isCustom?P&&((F=c==null?void 0:c.customCardPreferences)==null?void 0:F.componentName)===w.id:s===w.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>C(w),"aria-label":w.label,"aria-pressed":!!M,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",M&&"bg-foreground/[0.08] font-medium text-foreground"),children:[D?e.jsx(D,{className:"h-3.5 w-3.5"}):e.jsx(Ms,{chartName:w.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:w.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:w.label})]},`${w.isCustom?"custom":"default"}-${w.id}`)})}),e.jsxs(t.Popover,{open:o,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":A,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:A}),e.jsx(ae.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",o&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:w=>w.preventDefault(),children:e.jsx(xa,{onChartSelect:w=>{a(w),d(!1)},onClose:()=>d(!1)})})]})]})}function wo(){const s=t.useEditorStore(u=>{var x,m;return(m=(x=u.card.preferences)==null?void 0:x.chartOptions)==null?void 0:m.indexAxis}),a=t.useEditorStore(u=>u.card.type),{setChartOrientation:r,setCardPreferences:o}=t.useEditorStore(u=>u.actions),d=u=>{if(r(u),a!=="bullet")return;const x=u==="y"?"horizontal":"vertical",m=t.useEditorStore.getState().card.preferences,f={...m||{},bulletConfig:{...(m==null?void 0:m.bulletConfig)||{},orientation:x}};o(f)};function c(){const u=s??"x",x=()=>{d(u==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="x"?e.jsx(ps,{className:"h-3.5 w-3.5"}):e.jsx(hs,{className:"h-3.5 w-3.5"})})}function i(){const u=()=>{d(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(ps,{className:"h-3.5 w-3.5"}):e.jsx(hs,{className:"h-3.5 w-3.5"})})}function l(){const u=s??"y",x=()=>{d(u==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="y"?e.jsx(hs,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?l():c()})}function Rs({className:s,triggerVariant:a="icon",label:r="Display Options"}){var N,b,v,k,P,C,S,A,I,E;const o=t.useEditorStore(w=>w.card),{setCardPreferences:d,updateCardInFrame:c,setCard:i}=t.useEditorActions(),[l,u]=y.useState(!1),x=((b=(N=o.preferences)==null?void 0:N.displayOptions)==null?void 0:b.showFilterInfo)??!0,m=((k=(v=o.preferences)==null?void 0:v.displayOptions)==null?void 0:k.showCardToolbar)??!0,f=((C=(P=o.preferences)==null?void 0:P.displayOptions)==null?void 0:C.showChrome)??!0,g=((A=(S=o.preferences)==null?void 0:S.displayOptions)==null?void 0:A.allowScroll)??!0,p=((E=(I=o.preferences)==null?void 0:I.displayOptions)==null?void 0:E.showInlineFilterBar)??!0,h=(w,D)=>{var V;const M={...o.preferences,displayOptions:{...(V=o.preferences)==null?void 0:V.displayOptions,[w]:D}};d(M);const F={...o,preferences:M};i(F),c(F)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:l,onOpenChange:u,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:w=>{h("showFilterInfo",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:w=>{h("showCardToolbar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:f,onCheckedChange:w=>{h("showChrome",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:g,onCheckedChange:w=>{h("allowScroll",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(n.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:w=>{h("showInlineFilterBar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function Fs({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){var S,A,I;const[o,d]=y.useState(!1),c=t.useEditorStore(E=>E.card),i=t.useEditorStore(E=>E.selectedConnectionId),{tokenProps:l}=n.useSemaphorContext(),{setCard:u}=t.useEditorActions(),x=t.useDashboardStore(E=>E.actions.removeCardInlineFilterValue),m=t.useDashboardStore(E=>E.actions.setCardInlineFilterValue),f=t.useEditorStore(E=>E.actions.removeCardInlineFilterValue),g=t.useEditorStore(E=>E.actions.setCardInlineFilterValue),p=t.useDashboardStore(E=>E.isVisualEditing),h=(c==null?void 0:c.inlineFilters)||[],N=((A=(S=l==null?void 0:l.params)==null?void 0:S.calendarContext)==null?void 0:A.tz)||((I=l==null?void 0:l.params)==null?void 0:I.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(E){var z,_,q,G,H,$,W;const w=((q=(_=(z=c==null?void 0:c.dataSource)==null?void 0:z.selectedEntities)==null?void 0:_[0])==null?void 0:q.database)||"",D=E.qualifiedFieldName||E.name;if(h.find(Q=>n.doesStoredFilterMatchField(Q,E)))return;const F=E.qualifiedFieldName?E.qualifiedFieldName.split(".").slice(0,-1).join("."):E.qualifiedEntityName||E.entityName,R=t.fmt(E.name),j=n.buildFilterFieldMeta(E),T=n.buildFilterSemanticContext(c==null?void 0:c.dataSource,{connectionId:i||((G=c==null?void 0:c.dataSource)==null?void 0:G.connectionId),connectionType:(H=c==null?void 0:c.dataSource)==null?void 0:H.connectionType}),L=n.isCalculatedFilterField(j),O=!!((($=c==null?void 0:c.dataSource)==null?void 0:$.mode)==="semanticDomain"&&((W=T==null?void 0:T.selectedEntities)!=null&&W.length||T!=null&&T.semanticDomainId)),B={id:t.v4(),column:D,title:E.label||E.name,dataType:E.dataType,table:E.entityName||"",database:w,qualifiedTableName:F,connectionId:i||"",operation:"in",sql:L||O?"":n.getDefaultFilterSql(E.dataType,F,R),fieldMeta:j,semanticContext:T,width:250};u({...c,inlineFilters:[...h,B]})}function v(E){const w=h.filter(D=>D.id!==E);u({...c,inlineFilters:w}),p?f(c.id,E):x(c.id,E)}function k(E,w){const D=h.map(R=>R.id===E?{...R,...w}:R);if(u({...c,inlineFilters:D}),!(Object.prototype.hasOwnProperty.call(w,"defaultValues")||Object.prototype.hasOwnProperty.call(w,"defaultDateFilter")))return;const F=D.find(R=>R.id===E);if(!F)return;const V=t.buildFilterValueFromDefaults(F,N);V?p?g(c.id,V):m(c.id,V):p?f(c.id,E):x(c.id,E)}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 C=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",C&&"w-full",s),children:e.jsxs(t.Popover,{open:o,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:C?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",h.length>0&&"text-primary"),children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),h.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:h.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":h.length>0}),children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),h.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:h.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",C&&"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:h})})})}),h.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:h.map(E=>e.jsx(To,{filter:E,onUpdate:w=>k(E.id,w),onRemove:()=>v(E.id)},E.id))})]})]})})]})})}function To({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:o=>a(o),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(ae.X,{className:"h-3 w-3"})})]})]})}const Eo={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function Io(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const ko={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function rs(s,a){return`${s}:${a}`}function Do(s,a,r){const o=new Set(r.filter(c=>c.target!=="sql_param").map(c=>rs(c.controlId,c.target))),d=a.map(c=>{const i=t.getCompatibleBindingTargetOptions({card:s,control:c}).map(m=>m.value),l=ko[c.type],x=[...l?[l]:[],...i.filter(m=>m!==l)].find(m=>!o.has(rs(c.id,m)));return x?{controlId:c.id,target:x}:null}).find(Boolean);return d?{controlId:d.controlId,target:d.target,mapping:{}}:null}function Ao({card:s,dashboardControls:a,bindings:r,onChange:o,availableFieldChoices:d,availableMetricChoices:c,suppressTransientStaleState:i=!1}){const l=[...a,...s.controls||[]],[u,x]=y.useState({}),m=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),f=t.getBindingTargetSuggestions(s),g=new Set(r.map(P=>rs(P.controlId,P.target))),p=l.some(P=>t.getCompatibleBindingTargetOptions({card:s,control:P}).some(C=>!g.has(rs(P.id,C.value)))),h=i?0:r.reduce((P,C)=>{const S=N(C.target),A=Object.values(C.mapping).filter(I=>{const E=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof I=="string"?I:I==null?void 0:I.id:typeof I=="string"?I:void 0;return typeof E=="string"&&!S.some(w=>w.value===E)}).length;return P+A},0);function N(P){var C,S,A,I;switch(P){case"config_metric_selector":return c?c.filter(E=>!!E.target).map(E=>({value:E.target.id,label:E.target.label||E.option.label,target:E.target})):((S=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:S.map(E=>({value:E.id,label:E.label||E.id,target:E})))||[];case"config_field_selector":return d?d.filter(E=>!!E.target).map(E=>({value:E.target.id,label:E.target.label||E.option.label,target:E.target})):((I=(A=s.config)==null?void 0:A.groupByColumns)==null?void 0:I.map(E=>({value:E.id,label:E.label||E.id,target:E})))||[];case"config_aggregation":return(f.config_aggregation||[]).map(E=>({value:E,label:E}));case"config_grain":return(f.config_grain||[]).map(E=>({value:E,label:E.charAt(0).toUpperCase()+E.slice(1)}));default:return[]}}const b=(P,C)=>{o(r.map((S,A)=>A!==P?S:C(S)))},v=P=>{o(r.filter((C,S)=>S!==P))},k=()=>{const P=Do(s,l,r);P&&o([...r,P])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const P=m.map(({controlId:C,paramId:S})=>{const A=l.find(I=>I.id===C);return A?{id:C,paramId:S,label:A.label,reference:`[[param.${S}]]`}:{id:C,paramId:S,label:C,reference:`[[param.${S}]]`}});return e.jsx("div",{className:"space-y-2",children:P.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]]`."}):P.map(C=>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:C.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:C.reference}),e.jsx(n.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[h>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:[h," ",h===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((P,C)=>{const S=f[P.target]||[],A=l.find(j=>j.id===P.controlId),I=A?t.ensureManualSource(A):null,E=(I==null?void 0:I.source.kind)==="manual"?I.source.options:[],w=N(P.target),D=Array.from(new Set([...E.map(j=>j.value),...Object.keys(P.mapping)])).map(j=>{const T=E.find(L=>L.value===j);return{value:j,label:(T==null?void 0:T.label)||j}}),M=`${P.controlId}-${P.target}-${C}`,F=u[M]??C===0,V=Object.keys(P.mapping).length,R=A!=null&&A.type?Eo[A.type]||A.type:null;return e.jsxs(n.Collapsible,{open:F,onOpenChange:j=>x(T=>({...T,[M]:j})),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:[F?e.jsx(ae.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(Ue.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:(A==null?void 0:A.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:V>0?`${V} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>v(C),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:D.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."}):w.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:D.map(j=>{const T=P.mapping[j.value],L=P.target==="config_metric_selector"||P.target==="config_field_selector"?typeof T=="string"?T:T==null?void 0:T.id:typeof T=="string"?T:void 0,O=!i&&typeof L=="string"&&!w.some(_=>_.value===L),B=Io(T,L),z=L&&O?[...w,{value:L,label:"Needs remap",target:T}]:w;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:j.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:L||"__none__",onValueChange:_=>b(C,q=>{if(q.target==="config_metric_selector"){const H={...q.mapping};if(_==="__none__")delete H[j.value];else{const $=z.find(W=>W.value===_);$!=null&&$.target?H[j.value]=$.target:delete H[j.value]}return{...q,mapping:H}}if(q.target==="config_field_selector"){const H={...q.mapping};if(_==="__none__")delete H[j.value];else{const $=z.find(W=>W.value===_);$!=null&&$.target?H[j.value]=$.target:delete H[j.value]}return{...q,mapping:H}}const G={...q.mapping};return _==="__none__"?delete G[j.value]:G[j.value]=_,{...q,mapping:G}}),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))]})]}),O?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",B?` · Previously: ${B}`:""]})]}):null]})]},`${P.controlId}-${P.target}-${j.value}`)})}),S.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",S.join(", ")]})]})})]},M)}),p?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:k,children:[e.jsx(n.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const Lo=[];function Os({className:s,triggerVariant:a="icon",label:r="Controls"}){var F,V;const{handleOpenChange:o,preventPassiveDismissDuringCreate:d,resolvedOpen:c,setIsCreateFlowActive:i}=Te.useCreateFlowOverlayState({}),l=t.useEditorStore(R=>R.card),u=t.useEditorStore(R=>R.frame),x=t.useDashboardStore(R=>R.dashboard),f=t.useDashboardStore(R=>R.dashboard.controls)||Lo,{setCard:g,updateCardInFrame:p}=t.useEditorActions(),[h,N]=y.useState(null);y.useEffect(()=>{c&&!h&&(l!=null&&l.id)&&N(l.id)},[l==null?void 0:l.id,c,h]),y.useEffect(()=>{!c&&h!==null&&N(null)},[c,h]);const b=y.useMemo(()=>h?(u==null?void 0:u.cards.find(R=>R.id===h))||((l==null?void 0:l.id)===h?l:void 0):l,[l,u==null?void 0:u.cards,h]),v=(b==null?void 0:b.controls)||[],k=b?t.collectDashboardControlIds(x,{excludeCardId:b.id}):f.map(R=>R.id),P=((b==null?void 0:b.controlBindings)||[]).filter(R=>R.target!=="sql_param"),C=n.buildCardControlUsageById({card:b,controls:v}),S={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((F=b==null?void 0:b.config)==null?void 0:F.groupByColumns)||[]).map(R=>[R.id,R]))},A={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((V=b==null?void 0:b.config)==null?void 0:V.metricColumns)||[]).map(R=>[R.id,R]))},I=S.choices.map(R=>({option:R,target:S.targetMap[R.value]})),E=A.choices.map(R=>({option:R,target:A.targetMap[R.value]})),w=(R,j)=>{if(!b)return;const T=(j==null?void 0:j.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:j.oldId,newId:j.newId}):(j==null?void 0:j.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:j.controlId}):b,L={...T,controls:R,controlBindings:t.syncStructuralBindingsWithControls(T.controlBindings,R)};p(L),(l==null?void 0:l.id)===L.id&&g(L)},D=R=>{if(!b)return;const j={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(R,b.controlBindings)};p(j),(l==null?void 0:l.id)===j.id&&g(j)},M=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",M&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:M?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(v.length>0||P.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),v.length+P.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:v.length+P.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":v.length>0||P.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),v.length+P.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:v.length+P.length})]})}),e.jsxs(t.PopoverContent,{className:t.cn("flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",M&&"z-[60]"),align:"end",onEscapeKeyDown:d,onPointerDownOutside:d,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(Te.ControlDefinitionListEditor,{scope:"card",card:b,controls:v,reservedControlIds:k,usageByControlId:C,availableFieldChoices:I,availableMetricChoices:E,onCreateFlowActiveChange:i,onChange:(R,j,T)=>w(R,T),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(Ao,{card:b,dashboardControls:f,bindings:P,onChange:D,availableFieldChoices:I,availableMetricChoices:E}):null]})})]})]})})}function ga({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:o=!0,showDisplayOptions:d=!0}={}){const c=t.useEditorStore(p=>p.card),i=t.useEditorStore(p=>{var h,N;return(N=(h=p.card)==null?void 0:h.preferences)==null?void 0:N.chartOptions}),l=n.getChartGridStyle(i),{setChartGrid:u}=t.useEditorActions();function x(){const p=["xy","none","x","y"],N=(p.indexOf(l)+1)%p.length;u(p[N])}const m=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(c.type),f=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(c.type);return m||f||r||o||d?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[m&&e.jsx(e.Fragment,{children:e.jsx(wo,{})}),f&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:x,className:"h-7 w-7 px-0",children:[(l==="xy"||!l)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),l==="x"&&e.jsx(As,{className:"h-3.5 w-3.5"}),l==="y"&&e.jsx(n.Rows3,{className:"h-3.5 w-3.5"}),l==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(Fs,{}),o&&e.jsx(Os,{}),d&&e.jsx(Rs,{})]}):null}function Mo({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var T,L,O,B,z;const o=t.useEditorStore(_=>_.frame),d=t.useEditorStore(_=>_.card),c=t.useEditorStore(_=>_.editorContext),i=(c==null?void 0:c.type)==="documentSection",{setFrame:l,setActiveTabCardId:u,setCard:x,updateCardInFrame:m,clearModeDrafts:f,initializeModeDrafts:g}=t.useEditorActions(),{manifest:p}=n.useCustomVisual(((T=r==null?void 0:r.customCardPreferences)==null?void 0:T.url)||""),h=(L=p==null?void 0:p.visuals)==null?void 0:L.find(_=>{var q;return _.name===((q=r==null?void 0:r.customCardPreferences)==null?void 0:q.componentName)}),b=n.resolveMultiInputType(r,h)==="multiple",v=(h==null?void 0:h.minInputs)??((O=r==null?void 0:r.customCardPreferences)==null?void 0:O.minInputs)??1,k=(h==null?void 0:h.maxInputs)??((B=r==null?void 0:r.customCardPreferences)==null?void 0:B.maxInputs),P=y.useMemo(()=>n.getCustomVisualInputCards({frame:o,configCard:r,isMultiInputVisual:b}),[o,r,b]),C=b?P.filter(Boolean).length:o.cards.length,S=i?!1:k?C<k:!0,A=C>Math.max(v||1,1),I=!!((z=r==null?void 0:r.customCardPreferences)!=null&&z.dataInputCardIds),E=(_,q)=>{_.dataTransfer.setData("tabIndex",q.toString())},w=_=>{_.preventDefault()},D=(_,q)=>{const G=_.dataTransfer.getData("tabIndex");if(G===q.toString())return;const H=Array.from(o.cards),[$]=H.splice(parseInt(G),1);H.splice(q,0,$),l({...o,cards:H})};function M(_){const q=(r==null?void 0:r.id)===_;if(!(I&&q?o.cards.length>1:A))return;let H=o.cards.filter(se=>se.id!==_);b&&!I&&(H=n.reindexSlotCards(H));const $=H[0],W={...o,cards:H,activeCardId:$.id},Q=_===d.id;Q&&f(),l(W),u($.id),x($),Q&&g($)}function F(_,q){if(!S)return;const G={...o,cards:[...o.cards,q],activeCardId:_.id};l(G),u(q.id)}function V(){if(i)return;if(b&&(r==null?void 0:r.id)===d.id){R(d);return}const _={...d,id:t.v4(),title:`${d.title} Copy`,tabTitle:`${d.tabTitle||d.title} Copy`,customCardPreferences:d.customCardPreferences?{...d.customCardPreferences,slotIndex:b?Math.max(-1,...P.map((q,G)=>n.getSlotIndexForCard(q,G)))+1:d.customCardPreferences.slotIndex}:void 0};F(d,_)}function R(_){var Q;if(i||!S)return;let q=b?"table":"bar",G="Title",H="";const $=b?Math.max(-1,...P.map((se,ue)=>n.getSlotIndexForCard(se,ue)))+1:C;if(b&&((Q=h==null?void 0:h.slots)!=null&&Q.length)){const se=n.getSlotDefinitionForIndex(h.slots,$);se&&(q=n.getSlotExpectedChartType(se),G=se.label||`Tab ${$+1}`,H=se.description||"")}const W={dataSource:_.dataSource,connectionId:_.connectionId,lastSelectedDatabase:_.lastSelectedDatabase,lastSelectedSchema:_.lastSelectedSchema,lastSelectedTable:_.lastSelectedTable,lastSelectedDatamodelId:_.lastSelectedDatamodelId,id:t.v4(),title:G,tabTitle:G,description:H,preferences:{onClickFilter:[{columnIndex:0,expression:""}],...q==="text"?{textVisualOptions:{richContent:t.createEmptyRichContent()}}:{}},type:q,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:$}}};F(_,W)}function j(_,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 G=q.displayTab===void 0?!1:!q.displayTab;x({...q,displayTab:G}),m({...q,displayTab:G})},children:q.displayTab===!0||q.displayTab===void 0?e.jsx(Ue.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:[o.cards.map((_,q)=>{var Q,se;const G=b?n.getSlotIndexForCard(_,q):-1,H=b&&((Q=h==null?void 0:h.slots)!=null&&Q.length)&&G>=0?n.getSlotDefinitionForIndex(h.slots,G):null,$=H?(Array.isArray(H.expectedType)?H.expectedType[0]:H.expectedType)||"table":_.type,W=b&&((se=h==null?void 0:h.slots)==null?void 0:se.length)&&h.slots.every(ue=>typeof ue.position=="number"||typeof ue.position=="string"&&!ue.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!b&&!i,onDragStart:b||i?void 0:ue=>E(ue,q),onDragOver:b||i?void 0:w,onDrop:b||i?void 0:ue=>D(ue,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&&H?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($,"size-3.5")}),e.jsx("span",{children:H.label||`Tab ${G+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:H.label}),H.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:H.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[H.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(H.expectedType)?H.expectedType.join(" / "):H.expectedType}),H.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:[j(o,_),e.jsx(n.Editable,{enabled:o.activeCardId===_.id,text:_.tabTitle||_.title,onSave:ue=>{x({...d,tabTitle:ue}),m({...d,tabTitle:ue})},children:_.tabTitle||_.title},_.id)]}),!i&&o.activeCardId===_.id&&!W&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ue=>{ue.stopPropagation(),V()}}),!i&&o.activeCardId===_.id&&(I&&(r==null?void 0:r.id)===_.id?o.cards.length>1:A)&&e.jsx(ae.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>M(_.id)})]},_.id)}),!i&&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(d),disabled:!S,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(Ue.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function Nt({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var te,de,Le,Me,Qe;const r=t.useEditorStore(re=>re.frame),o=t.useEditorStore(re=>re.card),[d,c]=y.useState(!1),i=y.useMemo(()=>n.findCustomVisualConfigCard(r,o),[r,o]),l=t.useEditorStore(re=>re.isSqlRunning);t.useEditorStore(re=>re.isDevMode);const{setFrame:u,setActiveTabCardId:x,setCard:m,setRunSql:f,mergeDraftsIntoCard:g,clearModeDrafts:p,initializeModeDrafts:h}=t.useEditorActions(),[N,b]=y.useState({}),[v,k]=y.useState(()=>new Set),{authToken:P}=n.useSemaphorContext(),C=t.getTokenParams(P==null?void 0:P.accessToken),{compiledAppearance:S}=t.useAppearance(),A=y.useMemo(()=>n.buildCustomCardTheme(S),[S]),{getCard:I,manifest:E,isLoading:w}=n.useCustomVisual(((te=i==null?void 0:i.customCardPreferences)==null?void 0:te.url)||""),D=(de=i==null?void 0:i.customCardPreferences)==null?void 0:de.componentName,M=D?I(D):null,F=(Le=E==null?void 0:E.visuals)==null?void 0:Le.find(re=>re.name===D),V=n.resolveMultiInputType(i,F),R=d&&V==="multiple"&&!!i,j=y.useMemo(()=>n.getCustomVisualInputCards({frame:r,configCard:i,isMultiInputVisual:!0}).map(je=>(je==null?void 0:je.id)===o.id?o:je),[r,i,o]),T=y.useMemo(()=>n.buildSlotOrderedCards(j),[j]),L=y.useMemo(()=>{const re=j.findIndex(je=>(je==null?void 0:je.id)===o.id);return re<0?-1:n.getSlotIndexForCard(o,re)},[j,o]),O=y.useMemo(()=>!i||V!=="multiple"||L<0?o.type:n.getEffectiveCardTypeForSlot(o,L,F==null?void 0:F.slots)??o.type,[i,V,L,o,F==null?void 0:F.slots]),B=y.useMemo(()=>R?{...o,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:O!==o.type?{...o,type:O}:o,[o,O,R]),{data:z,isLoading:_,isFetching:q,isError:G,errorMessage:H,errorSql:$}=n.useEditorCardQuery(B),{handleOpenInEditor:W,handleDebugWithAssistant:Q}=Ls(H,$||o.sql||o.python),se=o.type==="text"&&((Qe=(Me=o.preferences)==null?void 0:Me.textVisualOptions)==null?void 0:Qe.isDynamicText)===!0&&!!H,ue=y.useCallback((re,je)=>{const Ce=n.normalizeMultiInputPayload(je);b(ne=>({...ne,[re]:Ce}))},[]),pe=y.useCallback((re,je)=>{k(Ce=>{const ne=new Set(Ce);return je?ne.add(re):ne.delete(re),ne})},[]),ge=v.size>0,ve=t.useInteractionStore(re=>re.interactionStates),Pe=t.useDashboardStore(re=>{var je;return(je=re.dashboard)==null?void 0:je.id}),Ve=t.useDashboardStore(re=>re.dashboard.filters),ee=t.useDashboardStore(re=>re.filterValues),xe=t.useDashboardStore(re=>re.selectedSheetId),Ee=t.useEditorStore(re=>re.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),qe=t.useEditorStore(re=>re.actions.setCardInlineFilterValue),$e=t.useEditorStore(re=>re.actions.removeCardInlineFilterValue),ce=y.useMemo(()=>i?n.buildInlineFilterNodes({card:i,sheetId:xe||"",inlineFilterValues:Ee,setInlineFilterValue:re=>qe(i.id,re),removeInlineFilterValue:re=>$e(i.id,re)}):[],[i,xe,Ee,qe,$e]),{cardFilters:Re,cardFilterValues:we}=y.useMemo(()=>i?n.calculateContextAwareFilters({card:i,interactionStates:ve,currentDashboardId:Pe,filters:Ve,filterValues:ee,selectedSheetId:xe}):{cardFilters:[],cardFilterValues:[]},[i,ve,Pe,Ve,ee,xe]);function ie(re){const je=r.cards.find(Ce=>Ce.id===re);je&&(Te.flushPendingEditorDrafts(),g(),K(re),x(re),p(),h(je))}function K(re){const je=t.useEditorStore.getState().card,Ce=t.useEditorStore.getState().frame,ne={...Ce,cards:Ce.cards.map(ke=>ke.id===je.id?je:ke),activeCardId:re};u(ne);const Ie=ne.cards.find(ke=>ke.id===re);Ie.sql&&f(!0),m(Ie)}function le(){if(w)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(!M)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const je=T.map((Ce,ne)=>n.getEffectiveCardTypeForSlot(Ce,ne,F==null?void 0:F.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[j.map((Ce,ne)=>{if(!Ce)return null;const Ie=n.getSlotIndexForCard(Ce,ne),ke=n.getEffectiveCardTypeForSlot(Ce,Ie,F==null?void 0:F.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:pe,onDataChange:ue,card:Ce,effectiveCardType:ke},`${Ce.id}-${Ie}`)}),ge&&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",ge&&"opacity-50"),children:e.jsx(y.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(M,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:T,slotTypes:je,multiInputData:N,params:C,theme:A,filters:Re,filterValues:[...we||[],...Ee||[]],inlineFilters:ce})})})})]})}function me(){var re;return R?le():s&&(a||!_&&!q&&!G&&!H)?s({card:o,data:z,isLoading:_,isFetching:q,isError:G}):o.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("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:o,data:z==null?void 0:z.records,isPending:_||q,isError:G,comparisonMetadata:(re=z==null?void 0:z.metadata)==null?void 0:re.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(o)&&e.jsx(n.CardSummary,{card:o,mode:"editor"})]})}):o.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"})}):se?e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-auto p-4",children:e.jsx(os,{error:H,errorSql:$||o.sql||o.python,onOpenInEditor:W,onDebugWithAssistant:Q,showFeedbackButton:!1})}):e.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 py-4",children:e.jsx(n.TextCard,{isLoading:l,card:o,data:z==null?void 0:z.records})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(ua,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ie,value:r.activeCardId,className:"flex grow flex-col",children:[R?e.jsx("div",{className:"mt-0 grow",children:me()}):r.cards.map(re=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:re.id,children:me()},re.id)),e.jsx(Mo,{isPreviewMode:R,onPreviewToggle:c,configCard:i})]})}function Ro({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 ba({fallbackPreview:s,records:a,title:r,isInspectorOpen:o,onInspectorOpenChange:d}){var V;const c=t.useEditorStore(R=>R.card),i=t.useEditorStore(R=>R.actions.setCard),l=t.useEditorStore(R=>R.actions.updateCardInFrame),u=t.normalizeDynamicRendererSource((V=c.dynamicCardPreferences)==null?void 0:V.rendererCode),[x,m]=y.useState(u),[f,g]=y.useState(u);y.useEffect(()=>{m(u),g(u)},[u,c.id]);const p=y.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),h=y.useMemo(()=>t.validateDynamicRendererSource(p),[p]),N=!!u,b=y.useMemo(()=>{var R;return t.buildCardWithVisualizationMode(c,f?"dynamic":"builtin",{rendererCode:f||void 0,artifactId:((R=c.dynamicCardPreferences)==null?void 0:R.artifactId)||c.id,title:r||c.title})},[c,f,r]),v=!!f,k=p!==f,P=f!==u,C=!p||!h.valid||k||P,S=p?h.valid?k?"Unapplied changes":"Pending save":"Needs attention":"Draft",A=!p||k||P?"outline":"destructive",I=p?h.valid?k?"The preview still reflects the last applied code until you apply this draft.":P?"Preview reflects pending changes. Accept changes to save them.":"":h.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function E(){if(!h.valid){n.ue.error(h.error||"Visual code is invalid.");return}g(p),n.ue.success("Dynamic preview updated.")}function w(){m(f)}function D(){var j;const R=t.buildCardWithVisualizationMode(c,f?"dynamic":"builtin",{rendererCode:f||void 0,artifactId:((j=c.dynamicCardPreferences)==null?void 0:j.artifactId)||t.v4(),title:r||c.title});i(R),l(R),d(!1),n.ue.success(f?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function M(){m(u),g(u),d(!1)}function F(){m(""),g("")}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:N?e.jsx(n.PersistedDynamicVisual,{card:c,records:a,title:r,layoutMode:"fill",fallback:s},u||"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(Ro,{onClick:()=>d(!0)})]})}),e.jsx(n.Dialog,{open:o,onOpenChange:R=>{if(!R){M();return}d(!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."})]}),C&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:A,children:S})]})}),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:v?e.jsx(n.PersistedDynamicVisual,{card:b,records:a,title:r,layoutMode:"fill",fallback:s},f||"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:!N&&!p,children:[e.jsx(ae.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:F,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:w,disabled:!k,children:[e.jsx(t.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:E,disabled:!k||!h.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:[I&&e.jsx("p",{className:t.cn("text-xs",h.valid?"text-muted-foreground":"text-destructive"),children:I}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!h.valid&&p&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:x,onValueChange:R=>m(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:I||"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:M,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:D,disabled:!P,children:"Accept changes"})]})]})]})})]})}function ja({onCustomize:s}){const a=t.useEditorStore(x=>x.card),r=t.useEditorStore(x=>x.frame),o=t.useEditorStore(x=>x.actions.setIsShowingVisual),{setVisualizationMode:d,setDynamicCardPreferences:c}=t.useEditorActions(),l=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const u=x=>{var m;x==="dynamic"&&!a.dynamicCardPreferences&&c(t.createEmptyDynamicCardPreferences(a.type,(m=a.preferences)==null?void 0:m.displayOptions)),d(x),o(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),u(l?"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:l,onCheckedChange:x=>u(x?"dynamic":"builtin"),onClick:x=>x.stopPropagation()})]}),l&&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]})}function va({sql:s,showCardDetails:a=!1,debugPayloads:r,className:o}){const[d,c]=y.useState(!1),i=t.useEditorStore(m=>m.isDevMode),{switchEditorMode:l,setRunSql:u}=t.useEditorActions(),x=()=>{l("dev",{sqlToLoad:s}),setTimeout(()=>{u(!0)},100)};return e.jsxs("div",{className:t.cn("flex max-h-full min-h-0 flex-1 flex-col overflow-hidden pt-3",o),children:[!i&&e.jsxs("div",{className:"mb-3 flex items-center gap-1.5",children:[e.jsxs(t.Button,{onClick:x,variant:"outline",size:"xs",children:[e.jsx(sa,{className:"mr-1.5 h-3 w-3"}),"View in SQL Editor"]}),a&&e.jsx(ca,{isOpen:d,onClick:()=>c(!d)})]}),d&&a&&e.jsx(da,{debugPayloads:r}),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:"max-h-[calc(min(70vh,640px)-2.75rem)] min-h-[80px] flex-1 overflow-auto 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 vs({children:s,visualAsideControl:a,mode:r="both",isDynamicInspectorOpen:o,onDynamicInspectorOpenChange:d}){var we;const c=n.useQueryClient(),i=t.useEditorStore(ie=>ie.frame),l=t.useEditorStore(ie=>ie.card),u=t.useEditorStore(ie=>ie.isDevMode),x=t.useEditorStore(ie=>ie.editorContext),m=(x==null?void 0:x.type)==="documentSection",f=t.useEditorStore(ie=>ie.isShowingVisual),g=t.useEditorStore(ie=>ie.actions.setIsShowingVisual),p=t.useDashboardStore(ie=>ie.isVisualEditing),{isConsoleMode:h}=n.useDashboardPreferences(),N=t.useEditorStore(ie=>ie.pythonStdOut),b=t.useEditorStore(ie=>ie.actions.setRunSql),v=Te.useEffectiveEditorCardType(),k=v==="table"||v==="detailTable"||v==="matrixTable",C=t.supportsRegularTableSettings(v)&&!!(a!=null&&a.onOpen),A=t.getVisualizationMode(l)==="dynamic",[I,E]=y.useState(!1),w=o??I,D=d??E,{setFrame:M,setCard:F,setActiveTabCardId:V,setCardPreferences:R,mergeDraftsIntoCard:j,clearModeDrafts:T,initializeModeDrafts:L,updatePageSize:O,setCardType:B}=t.useEditorActions(),z=y.useMemo(()=>v!==l.type?{...l,type:v}:l,[l,v]),{data:_,isLoading:q,isFetching:G,errorMessage:H,errorSql:$,refetch:W,queryKey:Q,pagination:se}=n.useEditorCardQuery(z),ue=y.useRef(Q);ue.current=Q;const{handleDebugWithAssistant:pe}=Ls(H,$),ge=y.useMemo(()=>(_==null?void 0:_.records)||[],[_==null?void 0:_.records]),{cardFilterValues:ve}=n.useCardFilterValues((l==null?void 0:l.id)??""),[Pe,Ve]=y.useState(!1);y.useEffect(()=>{G||Ve(!1)},[G]),y.useEffect(()=>{k&&!f&&!u&&!h&&g(!0)},[h,u,k,f,g]);function ee(ie,K){var te,de;const le={...l,paginationConfig:{page:ie+1,pageSize:K}};F(le);const me={...i,cards:i.cards.map(Le=>Le.id===l.id?le:Le)};M(me),l.sql&&((de=(te=l.preferences)==null?void 0:te.tablePrefs)!=null&&de.enableDevModePagination)&&b(!0)}function xe(ie){var te,de,Le,Me,Qe;const K=n.sortStateToSortByColumns(ie,(te=l.config)==null?void 0:te.metricColumns,(de=l.config)==null?void 0:de.groupByColumns,(Le=l.config)==null?void 0:Le.detailColumns),le={...l,config:{...l.config||{},sortByColumns:K}};F(le);const me={...i,cards:i.cards.map(re=>re.id===l.id?le:re)};M(me),l.sql&&((Qe=(Me=l.preferences)==null?void 0:Me.tablePrefs)!=null&&Qe.enableDevModePagination)&&b(!0)}function Ee(){var K;const ie=JSON.stringify(_==null?void 0:_.records,null,2);typeof navigator>"u"||!((K=navigator.clipboard)!=null&&K.writeText)||navigator.clipboard.writeText(ie).catch(le=>{console.error("Failed to copy JSON",le)})}function qe(){const ie=JSON.stringify(_==null?void 0:_.records,null,2),K=new Blob([ie],{type:"application/json"}),le=URL.createObjectURL(K),me=document.createElement("a");me.href=le,me.download=`${l.title}.json`,me.click()}function $e(){const K=[Object.keys(_==null?void 0:_.records.reduce((de,Le)=>({...de,...Le}),{})).join(","),...((_==null?void 0:_.records)||[]).map(de=>Object.values(de).join(","))].join(`
182
+ `),le=new Blob([K],{type:"text/csv"}),me=URL.createObjectURL(le),te=document.createElement("a");te.href=me,te.download=`${l.title}.csv`,te.click()}if(!l)return e.jsx(e.Fragment,{children:"No Active Card"});const ce=r==="both"||r==="toolbar",Re=r==="both"||r==="canvas";return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",r==="toolbar"?"h-auto pb-1":t.cn("h-full",!k&&"pt-2")),children:[ce&&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:!m&&!A&&e.jsx(fa,{selectedChart:l.type,onChartChange:ie=>B(ie),compactMore:!0})})}),!f&&e.jsx("div",{className:"grow"}),!q&&!G&&!H&&(_==null?void 0:_.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:"Executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",className:"max-h-[min(70vh,640px)] w-[500px] overflow-hidden p-0",children:e.jsx(va,{sql:_.sql})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,ve&&ve.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:ve.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(ve,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:q||G,className:"h-7 w-7 px-0",onClick:()=>{if(Ve(!0),u){Te.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:ue.current,exact:!0}),b(!0)},0);return}W()},children:e.jsx(na,{className:t.cn("h-3.5 w-3.5",{"animate-spin":Pe})})}),!A&&e.jsx(ga,{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}),"Settings"]}),(u||h)&&e.jsx(Po,{}),(u||h)&&k&&e.jsx(Oo,{}),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:[e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!A&&!["table","detailTable","custom"].includes(l.type)&&p&&e.jsx(fo,{triggerVariant:"menu",className:"w-full"}),e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"}),C&&e.jsxs(n.DropdownMenuItem,{onSelect:()=>{var ie;return(ie=a==null?void 0:a.onOpen)==null?void 0:ie.call(a,"style")},className:"gap-2 text-[13px]",children:[e.jsx(xr,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(ja,{onCustomize:()=>D(!0)}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{onSelect:$e,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{onSelect:qe,className:"gap-2 text-[13px]",children:[e.jsx(rr,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{onSelect:Ee,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]})]})]})]}),Re&&(f?A?e.jsx(Nt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(ba,{fallbackPreview:e.jsx(Nt,{}),records:ge,title:l.title,isInspectorOpen:w,onInspectorOpenChange:D})}):e.jsx(Nt,{}):e.jsxs(n.ResizablePanelGroup,{className:t.cn(N&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[N&&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:N&&e.jsx(Fo,{})}),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":N}),children:[Array.isArray(_==null?void 0:_.records)&&!H&&(u?e.jsx(oo,{data:_.records,card:z,paginationMetadata:se,onPaginationChange:ee,onPageSizePreferenceChange:O,onSortChange:xe,isLoading:q||G}):_.records.length>0?e.jsx(n.TableVisual,{card:l,data:ge,totalsByColumnId:_==null?void 0:_.tableTotalsByColumnId,comparisonMetadata:(we=_==null?void 0:_.metadata)==null?void 0:we.comparisonMetadata,paginationMetadata:se,onPaginationChange:ee,onSortChange:xe,isLoading:q||G}):null),H&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(os,{error:H,errorSql:$||l.sql||l.python,onDebugWithAssistant:pe,showFeedbackButton:!1})})]})]}))]})}function Fo(){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 Oo(){var l,u,x,m,f,g,p,h;const s=t.useEditorStore(N=>N.card),a=t.useEditorStore(N=>N.actions.setCard),r=t.useEditorStore(N=>N.actions.setRunSql),o=t.useEditorStore(N=>N.actions.setCardPreferences),d=t.useEditorStore(N=>N.actions.updateCardInFrame),c=y.useMemo(()=>{var N,b;return n.getTablePageSizeOptions((b=(N=s.preferences)==null?void 0:N.tablePrefs)==null?void 0:b.pageSize)},[(u=(l=s.preferences)==null?void 0:l.tablePrefs)==null?void 0:u.pageSize]),i=n.resolveTablePageSize((m=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:m.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:((g=(f=s.preferences)==null?void 0:f.tablePrefs)==null?void 0:g.enableDevModePagination)??!1,onCheckedChange:N=>{var b;o({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:N}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-[13px]",children:"Paginate"}),((h=(p=s.preferences)==null?void 0:p.tablePrefs)==null?void 0:h.enableDevModePagination)&&e.jsxs(t.Select,{value:String(i),onValueChange:N=>{var k,P,C;const b=Number(N),v={...s,preferences:{...s.preferences,tablePrefs:{...(k=s.preferences)==null?void 0:k.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(v),d(v),s.sql&&((C=(P=s.preferences)==null?void 0:P.tablePrefs)!=null&&C.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(N=>e.jsx(t.SelectItem,{value:String(N),children:N},N))})]})]})}function Po(){const s=t.useEditorStore(r=>r.isShowingVisual),a=t.useEditorStore(r=>r.actions.setIsShowingVisual);return e.jsxs(n.Toggle,{pressed:!s,onPressedChange:r=>{a(!r)},variant:"default",size:"sm","aria-label":"Toggle results",className:"h-7 gap-1.5 rounded-[5px] border border-border/60 px-2.5 text-[12px] text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(t.Table2,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Results"})]})}function Ze({value:s,onCommit:a,type:r="text",placeholder:o,className:d}){const[c,i]=y.useState(s),l=y.useRef(!1);y.useEffect(()=>{i(s)},[s]);const u=()=>{if(l.current){l.current=!1;return}c!==s&&a(c)},x=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(l.current=!0,i(s),m.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:c,onChange:m=>i(m.target.value),onBlur:u,onKeyDown:x,className:d})}function gt({defaultValue:s,label:a,options:r,value:o,onValueChange:d,className:c,icon:i,showPlaceholderLabel:l=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:d,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:[i&&e.jsx("span",{children:i}),l&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function Vo(s,a){return n.getSlotDefinitionForIndex(s,a)||null}function qt(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,o,d]=a;return`Tabs ${Number(o)+1}-${Number(d)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function Bo(s){return s?Array.isArray(s)?s:[s]:[]}function ys(s){var o,d;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const a=!!((d=s.sql)!=null&&d.trim()),r=At.hasValidCardConfig(s.config);return a||r}function _o({slots:s,cards:a,minInputs:r}){const o=[],d=a.filter(Boolean).length;return r&&d<r&&o.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 u=a[c.position];ys(u)||o.push({type:"missing-required",message:`${qt(c.position)} ("${c.label}") is required but has no data configured.`});return}const i=c.position.match(/^(\d+)-(\d+)$/);if(i){const[,u,x]=i.map(Number);for(let m=u;m<=x;m+=1){const f=a[m];if(!ys(f)){o.push({type:"missing-required",message:`${qt(m)} ("${c.label}") is required but has no data configured.`});break}}return}const l=c.position.match(/^(\d+)\+$/);if(l){const u=Number(l[1]);if(a.length<=u){o.push({type:"missing-required",message:`${qt(u)} ("${c.label}") is required but has no data configured.`});return}for(let x=u;x<a.length;x+=1){const m=a[x];if(!ys(m)){o.push({type:"missing-required",message:`${qt(x)} ("${c.label}") is required but has no data configured.`});break}}}}),a.forEach((c,i)=>{if(!c)return;const l=Vo(s,i);if(!l||!l.expectedType)return;const u=Bo(l.expectedType);u.length!==0&&(u.includes(c.type)||o.push({type:"wrong-type",message:`${qt(i)} ("${l.label}") expects ${u.join(", ")}, but is configured as ${c.type}.`}))})),o}const zo={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 ya(){var F,V,R;const s=t.useEditorStore(j=>j.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],o=t.useEditorStore(j=>j.card),d=t.useEditorStore(j=>j.frame),{setCustomCardPreferences:c}=t.useEditorActions(),i=y.useMemo(()=>n.findCustomVisualConfigCard(d,o),[d,o]),l=i==null?void 0:i.customCardPreferences,{components:u,manifest:x}=n.useCustomVisual((l==null?void 0:l.url)||(s==null?void 0:s.url)||""),m=(F=x==null?void 0:x.visuals)==null?void 0:F.find(j=>j.name===((l==null?void 0:l.componentName)||(s==null?void 0:s.componentName))),g=n.resolveMultiInputType(i||o,m)==="multiple",p=!!i&&i.id===o.id,h=(m==null?void 0:m.minInputs)??((V=i==null?void 0:i.customCardPreferences)==null?void 0:V.minInputs),N=(m==null?void 0:m.maxInputs)??((R=i==null?void 0:i.customCardPreferences)==null?void 0:R.maxInputs),b=y.useMemo(()=>n.getCustomVisualInputCards({frame:d,configCard:i||o,isMultiInputVisual:g}),[d,i,o,g]),v=y.useMemo(()=>n.buildSlotOrderedCards(b),[b]),k=y.useMemo(()=>v.map((j,T)=>{if(!j)return null;const L=n.getSlotIndexForCard(j,T),O=n.getEffectiveCardTypeForSlot(j,L,m==null?void 0:m.slots);return{...j,type:O??j.type}}),[v,m==null?void 0:m.slots]),P=y.useMemo(()=>_o({slots:m==null?void 0:m.slots,cards:k,minInputs:h}),[m==null?void 0:m.slots,k,h]),C=y.useMemo(()=>{const j=b.findIndex(T=>(T==null?void 0:T.id)===o.id);return j<0?-1:n.getSlotIndexForCard(o,j)},[b,o]);function S(j){if(typeof j=="number")return`Tab ${j+1}`;const T=j.match(/^(\d+)-(\d+)$/);if(T){const[,O,B]=T;return`Tabs ${Number(O)+1}-${Number(B)+1}`}const L=j.match(/^(\d+)\+$/);return L?`Tabs ${Number(L[1])+1}+`:`Tab ${j}`}function A(j){return j?(Array.isArray(j)?j:[j]).join(", "):null}function I(j,T,L=[],O="",B,z,_){const q=E({key:T,defaultValue:O,settingsValue:z,sourceCard:_});return j==="input"?e.jsx(Ze,{className:`h-8 w-full ${t.removeRing}`,value:String(q??""),onCommit:G=>{w({key:T,value:G,settingsField:B,settingsValue:z,sourceCard:_})}},T):j==="select"?e.jsx(gt,{className:"h-8 w-full",label:"",options:L,value:String(q!==void 0?q:O??""),onValueChange:G=>{w({key:T,value:G,settingsField:B,settingsValue:z,sourceCard:_})}}):null}function E({key:j,defaultValue:T,settingsValue:L,sourceCard:O}){const B=L==null?void 0:L[j];return B!==void 0?B:j==="title"&&(O==null?void 0:O.title)!==void 0?O.title:j==="description"&&(O==null?void 0:O.description)!==void 0?O.description:T}function w({key:j,value:T,settingsField:L,settingsValue:O,sourceCard:B}){const z={...O||{}},_=j==="title"&&(B==null?void 0:B.title)!==void 0,q=j==="description"&&(B==null?void 0:B.description)!==void 0;_&&T===String((B==null?void 0:B.title)??"")||q&&T===String((B==null?void 0:B.description)??"")?delete z[j]:z[j]=T,c({...s||{},[L]:z})}function D({settingsSchema:j,settingsField:T,settingsValue:L,sourceCard:O,headerLabel:B}){const z=Object.entries(j||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),z.map(([_,q])=>{var G;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}),((G=q.docs)==null?void 0:G.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})})]})})]}),I(q.ui,_,q.options,q.defaultValue,T,L,O)]},_)})]})}function M(){return e.jsxs(e.Fragment,{children:[g&&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:m!=null&&m.slots&&m.slots.length>0?e.jsx("div",{className:"space-y-3",children:m.slots.map((j,T)=>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:S(j.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:j.label})]}),j.description&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[A(j.expectedType)&&e.jsxs("span",{children:["Expected: ",A(j.expectedType)]}),j.required&&e.jsx("span",{children:"Required"})]})]},`${j.label}-${T}`))}):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."}),(h||N)&&e.jsxs("p",{children:[h?`Min ${h} tabs`:"",h&&N?" • ":"",N?`Max ${N} tabs`:""]})]})})]}),g&&P.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:P.map((j,T)=>e.jsx("li",{children:j.message},`${j.type}-${T}`))})})}),m&&!g&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:D({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),m&&g&&(m.settings||m.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[p&&m.settings&&e.jsx("div",{className:"px-2",children:D({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:i||o,headerLabel:"Global Settings"})}),m.slotSettings&&e.jsx("div",{className:"px-2",children:D({settingsSchema:m.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const j=o.tabTitle||o.title,T=C>=0?C:0,L=p?"Slot 0":`Slot ${T}`;return j?`${L}: ${j} Settings`:`${L} 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:[(!g||p)&&e.jsx(gt,{icon:e.jsx(ta,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(l==null?void 0:l.url)||"",onValueChange:j=>c({...s||{url:"",componentName:""},url:j})}),g&&!p&&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&&(!g||p)&&e.jsx(e.Fragment,{children:u&&e.jsx(gt,{icon:e.jsx(ar,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.map(j=>({value:j.name,label:j.name})))||[],value:s.componentName||"",onValueChange:j=>{var O;const T=(O=x==null?void 0:x.visuals)==null?void 0:O.find(B=>B.name===j),L=u==null?void 0:u.find(B=>B.name===j);c({...s,componentName:j,visualType:(T==null?void 0:T.visualType)||(L==null?void 0:L.type)||"single",minInputs:T==null?void 0:T.minInputs,maxInputs:T==null?void 0:T.maxInputs,pluginChartType:T==null?void 0:T.chartType})}})})]})})]}),((l==null?void 0:l.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:(m==null?void 0:m.name)||"Settings"}),(m==null?void 0:m.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,onClick:j=>j.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:[m.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:m.docs.description}),m.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:zo,children:m.docs.dataSchema})})]}),(()=>{var T;const j=(T=m.docs)==null?void 0:T.useCases;return!j||j.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:j.map((L,O)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:L})]},O))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:M()})]})]})}function qo({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function o(i,l,u){const x=[...s];x[i]={...x[i],[l]:u},a(x)}function d(i){const l=[...s];l.splice(i,1),a(l)}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((i,l)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:u=>o(l,"start",u.target.value),value:i.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:i.end,onChange:u=>o(l,"end",u.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:u=>o(l,"color",u.target.value),value:i.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:()=>d(l),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(ae.X,{className:"size-3"})})]},l))]})}function $o(){var m,f,g,p,h;const s=t.useEditorStore(N=>N.card.preferences),a=t.useEditorStore(N=>N.actions.setCardPreferences),r=t.useEditorStore(N=>N.card),o=At.hasValidCardConfig(r.config),d=t.useEditorStore(N=>N.actions.setNumberFormat);t.useEditorStore(N=>{var b,v;return(v=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:v.decimalPlaces});const c=t.useEditorStore(N=>{var b,v;return(v=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:v.locale}),i=t.useEditorStore(N=>{var b,v;return(v=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:v.currency});t.useEditorStore(N=>N.actions.setFilterOnClickField);const l=t.useEditorStore(N=>{var b,v;return(v=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:v.colorRanges})||[],u=t.useEditorStore(N=>N.actions.setColorRanges),x=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(N=>N.currency))];return e.jsxs("div",{children:[!o&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"query-kpi-format-number",checked:!!((m=s==null?void 0:s.formatNumber)!=null&&m.enabled),onCheckedChange:N=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:N}})}}),e.jsx(t.Label,{htmlFor:"query-kpi-format-number",className:"text-xs",children:"Format number"})]}),(((f=s==null?void 0:s.formatNumber)==null?void 0:f.enabled)===!0||o)&&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:N=>{var b,v,k;return d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((v=s==null?void 0:s.formatNumber)==null?void 0:v.currency)||"",N,((k=s==null?void 0:s.formatNumber)==null?void 0:k.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(N=>e.jsx(t.SelectItem,{value:N.locale,children:N.locale},N.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:i||"none",onValueChange:N=>{var b,v,k;console.log("currency",N),d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,N==="none"?"":N,((v=s==null?void 0:s.formatNumber)==null?void 0:v.locale)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.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(N=>e.jsx(t.SelectItem,{value:N,children:N},N))]})})]})]})]}),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:((p=(g=s==null?void 0:s.formatNumber)==null?void 0:g.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:N=>{var b,v,k;return d(Number(N),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.locale)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.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(N=>e.jsx(t.SelectItem,{value:N,children:N},N))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((h=s==null?void 0:s.formatNumber)==null?void 0:h.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:N=>{var b,v,k;return d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((v=s==null?void 0:s.formatNumber)==null?void 0:v.currency)||"",((k=s==null?void 0:s.formatNumber)==null?void 0:k.locale)||"",N.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(qo,{colorRanges:l,setColorRanges:u})]})]})}const Ko={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 Na(s){return Ko[s]}function Uo({chartType:s,showDocsLink:a=!0}){const r=Na(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((o,d)=>e.jsxs("tr",{className:d<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[o.name,o.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:o.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:o.description||"—"})]},o.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:o=>o.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 Go({chartType:s}){return Na(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(Uo,{chartType:s})})]}):null}function Ps({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-medium",children:a}),e.jsx(Go,{chartType:s})]})}function Ho(){const s=t.useEditorStore(d=>!At.hasValidCardConfig(d.card.config)),a=t.useEditorStore(d=>{var c,i;return((i=(c=d.card.preferences)==null?void 0:c.kpiVisualOptions)==null?void 0:i.queryComparisonPolarity)??Ln.DEFAULT_METRIC_COMPARISON_POLARITY}),r=t.useEditorStore(d=>d.actions.setCardPreferences),o=d=>{const c=t.useEditorStore.getState().card.preferences??{},i={...c.kpiVisualOptions,queryComparisonPolarity:d===Ln.DEFAULT_METRIC_COMPARISON_POLARITY?void 0:d};r({...c,kpiVisualOptions:i})};return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Ps,{chartType:"kpi"}),e.jsx("section",{children:e.jsx($o,{})}),s&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx(t.Label,{htmlFor:"query-kpi-favorable-direction",className:"text-xs",children:"Favorable direction"}),e.jsxs(t.Select,{value:a,onValueChange:d=>o(d),children:[e.jsx(t.SelectTrigger,{id:"query-kpi-favorable-direction",className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Applies when the query returns current and comparison values."})]})]})}function Un({children:s,summary:a,open:r,className:o}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",o),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 Qo(){const[s,a]=y.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:d}=t.useEditorStore(x=>x.actions),c=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var m;return(m=x.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),y.useEffect(()=>{c&&a(new Array(c.length).fill(!1))},[c]);function i(x,m){var f,g;m?r!=null&&r.onClickFilter&&((f=r==null?void 0:r.onClickFilter)==null?void 0:f.length)>0?d({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):d({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(d({...r,onClickFilter:(g=r==null?void 0:r.onClickFilter)==null?void 0:g.filter(p=>p.columnIndex!==x)}),a(p=>{const h=[...p];return h[x]=!1,h}))}function l(x,m){var g;const f=(g=r==null?void 0:r.onClickFilter)==null?void 0:g.map(p=>p.columnIndex===x?{...p,expression:m.target.value}:p);d({...r,onClickFilter:f})}function u(x){var m,f,g,p;if(s!=null&&s[x]||(f=(m=r==null?void 0:r.onClickFilter)==null?void 0:m.find(h=>h.columnIndex===x))!=null&&f.expression)return e.jsx(t.Input,{value:(p=(g=r==null?void 0:r.onClickFilter)==null?void 0:g.find(h=>h.columnIndex===x))==null?void 0:p.expression,onChange:h=>l(x,h),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,m)=>{var f,g;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:!!((f=r==null?void 0:r.onClickFilter)!=null&&f.find(p=>p.columnIndex===m)),onCheckedChange:p=>i(m,p)}),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:((g=r==null?void 0:r.onClickFilter)==null?void 0:g.find(p=>p.columnIndex===m))&&e.jsx(n.Pencil,{onClick:()=>{a(p=>{const h=[...p];return h[m]=!p[m],h})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},x)})})}const Wo=[{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"}],Yo=["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"],Jo=Yo.map(s=>({label:s,value:s}));function Xo(){var u,x,m,f,g,p,h,N,b,v,k,P,C,S,A,I,E,w;const s=t.useEditorStore(D=>D.card),a=(x=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,o]=y.useState(((f=(m=s==null?void 0:s.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:c}=n.useTopoJson(s),i=Object.keys((c==null?void 0:c.objects)||{}).map(D=>({label:D,value:D}))||[],l=[{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(Ps,{chartType:"map"}),e.jsx(Un,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(gt,{className:"h-9",options:l,onValueChange:D=>{console.log("value",D),d({...s.preferences,mapVisualOptions:{topoJsonUrl:D}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:D=>{o(D.target.value)},onBlur:()=>{var D;console.log("onBlur",r),d({...s.preferences,mapVisualOptions:{...(D=s.preferences)==null?void 0:D.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(gt,{className:"h-9",options:i,value:((p=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:D=>{var M;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,objectKey:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(gt,{className:"h-9",options:Wo,value:((N=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:N.projection)||"",label:"Projection",onValueChange:D=>{var M;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projection:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(gt,{className:"h-9",options:Jo,value:((v=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:v.colorScale)||"",label:"Select Color Scale",onValueChange:D=>{var M;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,colorScale:D}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Un,{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:((P=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:P.projectionScale)||1,onChange:D=>{var M;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionScale:Number(D.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((A=(S=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:A[0])||0,onChange:D=>{var M,F,V,R;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionOffset:[Number(D.target.value),((R=(V=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:V.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:((w=(E=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[1])||0,onChange:D=>{var M,F,V,R;d({...s.preferences,mapVisualOptions:{...(M=s.preferences)==null?void 0:M.mapVisualOptions,projectionOffset:[((R=(V=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:V.projectionOffset)==null?void 0:R[0])||0,Number(D.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Qo,{})]})}const Zo={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function el(s){return s&&(Zo[s]??s)}function Ca({value:s,onChange:a,showPosition:r=!1}){const o=s.colors||{};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Select,{value:s.displayMode||"difference",onValueChange:d=>a({displayMode:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"difference",children:"Difference"}),e.jsx(t.SelectItem,{value:"percent_change",children:"Percent change"}),e.jsx(t.SelectItem,{value:"both",children:"Both"}),e.jsx(t.SelectItem,{value:"ratio",children:"Ratio (current ÷ comparison)"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"comparison-precision",className:"text-xs",children:"Percent/ratio precision"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"0 through 6 decimals"})]}),e.jsx(t.Input,{id:"comparison-precision",type:"number",min:0,max:6,step:1,value:s.precision??"",placeholder:"Default",onChange:d=>{if(d.target.value===""){a({precision:void 0});return}const c=Number(d.target.value);Number.isInteger(c)&&c>=0&&c<=6&&a({precision:c})},className:"h-7 w-16 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Indicator"}),e.jsxs(t.Select,{value:s.indicatorStyle||"arrow_badge",onValueChange:d=>a({indicatorStyle:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"arrow_badge",children:"Arrow + badge"}),e.jsx(t.SelectItem,{value:"arrow",children:"Arrow"}),e.jsx(t.SelectItem,{value:"badge",children:"Badge"}),e.jsx(t.SelectItem,{value:"none",children:"None"})]})]})]}),r&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Position"}),e.jsxs(t.Select,{value:s.position||"right",onValueChange:d=>a({position:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",children:"Right"}),e.jsx(t.SelectItem,{value:"left",children:"Left"}),e.jsx(t.SelectItem,{value:"top",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-color",className:"text-xs",children:"Use sentiment color"}),e.jsx(t.Switch,{id:"comparison-color",size:"xs",checked:s.showColor!==!1,onCheckedChange:d=>a({showColor:d})})]}),s.showColor!==!1&&e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase","#16a34a"],["decrease","Decrease","#dc2626"],["neutral","No change","#6b7280"]].map(([d,c,i])=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:c}),e.jsx(n.ColorField,{value:el(o[d]||i),onChange:l=>a({colors:{...o,[d]:l||i}}),defaultValue:i,ariaLabel:`${c} color`,allowEmpty:!1})]},d))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-conditional-label",className:"text-xs",children:"Different label per direction"}),e.jsx(t.Switch,{id:"comparison-conditional-label",size:"xs",checked:s.conditionalLabel===!0,onCheckedChange:d=>a({conditionalLabel:d})})]}),s.conditionalLabel?e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase"],["decrease","Decrease"],["neutral","No change"]].map(([d,c])=>{var i;return e.jsx(t.Input,{"aria-label":`${c} label`,value:((i=s.conditionalLabels)==null?void 0:i[d])||c,onChange:l=>a({conditionalLabels:{...s.conditionalLabels,[d]:l.target.value}}),className:"h-7 text-xs"},d)})}):e.jsx(t.Input,{"aria-label":"Comparison label",value:s.labelName||"",onChange:d=>a({labelName:d.target.value}),placeholder:"Previous",className:"h-7 text-xs"})]})}function tl(){var f,g,p,h,N;const s=t.useEditorStore(b=>b.card),{setCardPreferences:a}=t.useEditorActions(),r=Te.useEffectiveEditorCardType(),o=((f=s.config)==null?void 0:f.metricColumns)||[],d=o.length===2&&(((g=s.config)==null?void 0:g.groupByColumns)||[]).length===0,c=o.some(b=>{var v;return((v=b.comparison)==null?void 0:v.mode)==="explicit"});if(!t.COMPARISON_PRESENTATION_SUPPORTED_CHART_TYPES.includes(r))return null;const l=((p=s.preferences)==null?void 0:p.comparisonPresentation)||{},u=b=>a({...s.preferences,comparisonPresentation:{...l,...b}}),x=r==="kpi"&&((h=s.preferences)==null?void 0:h.metricPairComparisonEnabled)===!0,m=c||x;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 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lr,{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:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"inherit-global-date-comparison",className:"text-xs",children:"Inherit Global Date comparison"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Author-set metric comparisons still take precedence."})]}),e.jsx(t.Switch,{id:"inherit-global-date-comparison",size:"xs",checked:((N=s.preferences)==null?void 0:N.inheritGlobalComparison)!==!1,onCheckedChange:b=>{const v={...s.preferences};b?delete v.inheritGlobalComparison:v.inheritGlobalComparison=!1,a(v)}})]}),r==="kpi"&&d&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-metric-pair-comparison",className:"text-xs",children:"Enable metric comparison"}),e.jsx(t.Switch,{id:"enable-metric-pair-comparison",size:"xs",checked:x,onCheckedChange:b=>a({...s.preferences,metricPairComparisonEnabled:b})})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"show-explicit-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-explicit-comparison",size:"xs",checked:l.showComparison!==!1,onCheckedChange:b=>u({showComparison:b})})]}),m&&e.jsx(Ca,{value:l,onChange:u,showPosition:r==="kpi"&&d})]})]})}function Sa({cardType:s,queryResultColumns:a,focusSection:r,focusRequestId:o}){var q,G,H;const d=t.useEditorStore($=>$.card),c=t.useEditorStore($=>$.queryResultColumns),i=t.useEditorStore($=>{var W;return(W=$.card)==null?void 0:W.preferences}),l=i==null?void 0:i.tablePrefs,u=t.useEditorStore($=>$.actions.setCardPreferences),x=t.useEditorStore($=>$.actions.updateTableConditionalFormatting),m=((q=d.config)==null?void 0:q.metricColumns)||[],f=s??d.type,g=a??c,p=d.type===f?d:{...d,type:f},h=n.getTableConditionalFormattingColumnOptions(p,g),N=n.getTableOutputColumnOptions(p,g),b=n.supportsTableConditionalFormatting(f),v=f==="table",k=f==="table",P=((G=h[0])==null?void 0:G.value)||"",C=n.normalizeConditionalFormatting((H=i==null?void 0:i.tablePrefs)==null?void 0:H.conditionalFormatting),S=n.resolveTablePresentationStyle(l),A=n.isEligibleFlatTableTotalsCard(p),I=n.hasFlatTableTotalsBehavior(p),[E,w]=y.useState("style");y.useEffect(()=>{if(r==="style"){w("style");return}if(r==="columns"&&k){w("columns");return}r==="conditional-formatting"&&b&&w("conditional-formatting")},[k,b,o,r]);const D=m.some($=>{var W;return((W=$.comparison)==null?void 0:W.mode)==="explicit"}),M=(i==null?void 0:i.comparisonPresentation)||{},F=$=>{u({...i,comparisonPresentation:{...M,...$}})},V=$=>{x({version:1,rules:$})},R=$=>{u({...i,tablePrefs:{...l,density:$}})},j=$=>{u({...i,tablePrefs:{...l,tableStyle:{...l==null?void 0:l.tableStyle,...$}}})},T=$=>{var W;j({totals:{...(W=l==null?void 0:l.tableStyle)==null?void 0:W.totals,...$}})},L=$=>{var W;u({...i,tablePrefs:{...l,tableStyle:{...l==null?void 0:l.tableStyle,totals:{...(W=l==null?void 0:l.tableStyle)==null?void 0:W.totals,enabled:$}}}})},O=($,W)=>{u({...i,tablePrefs:{...l,columnVisibility:n.setTableColumnVisibility(l==null?void 0:l.columnVisibility,$,W)}})},B=()=>{u({...i,tablePrefs:{...l,columnVisibility:n.showAllTableColumns()}})},z=()=>{u({...i,tablePrefs:{...l,density:n.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:n.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:A?I:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},_=D?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Comparison"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(t.Label,{htmlFor:"show-table-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-table-comparison",size:"xs",checked:M.showComparison!==!1,onCheckedChange:$=>F({showComparison:$})})]}),e.jsx(Ca,{value:M,onChange:F})]}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:E,onValueChange:$=>w($),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),k?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!b,children:"Conditional formatting"})]}),e.jsx(t.TabsContent,{value:"style",className:"mt-0",children:e.jsx(n.TablePresentationSettings,{style:S,onDensityChange:R,onStyleChange:j,showFullStyle:v,showBorderStyle:!1,totals:v&&A?{enabled:I,onEnabledChange:L,onStyleChange:T}:void 0,extraSection:_,onReset:v?z:void 0})}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:k?e.jsx(n.TableColumnVisibilitySettings,{columns:N,columnVisibility:l==null?void 0:l.columnVisibility,onColumnVisibilityChange:O,onShowAllColumns:B}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Column visibility is available for table cards."})}),e.jsx(t.TabsContent,{value:"conditional-formatting",className:"mt-0",children:b?P?e.jsx(n.DataTableConditionalFormattingSettings,{columnId:P,availableColumns:h,conditionalRules:C.rules,onConditionalRulesChange:V,startRulesWithNoTrigger:!0}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Run the query to configure conditional formatting."}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Conditional formatting is available for table cards."})})]})})}function sl(){var d;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:a}=t.useEditorStore(c=>c.actions),r=(d=s==null?void 0:s.textVisualOptions)!=null&&d.isDynamicText?"dynamic":"static";function o(c){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:c==="dynamic"}})}return e.jsx(t.Tabs,{value:r,onValueChange:o,children:e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"static",children:"Static"}),e.jsx(t.TabsTrigger,{value:"dynamic",children:"Dynamic"})]})})}function nl(){return e.jsxs("div",{className:"space-y-2 px-6 py-4",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Text mode"}),e.jsx(sl,{}),e.jsx("p",{className:"pt-1 text-[12px] leading-[1.55] text-muted-foreground",children:"Static text is authored inline. Dynamic text reads from the first cell of the card's query."})]})}function al({color:s,onColorChange:a,onClose:r}){const[o,d]=y.useState(0),[c,i]=y.useState(100),[l,u]=y.useState(50),[x,m]=y.useState(s);y.useEffect(()=>{const b=Gn(s);if(b){const v=Hn(b.r,b.g,b.b);d(v.h),i(v.s),u(v.l),m(s)}},[s]);const f=b=>{d(b),p(b,c,l)},g=b=>{const v=b.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(b.clientX-v.left)/v.width)),P=Math.max(0,Math.min(1,(b.clientY-v.top)/v.height)),C=k*100,S=(1-P)*100;i(C),u(S),p(o,C,S)},p=(b,v,k)=>{const P=ol(b,v,k),C=rl(P.r,P.g,P.b);m(C)},h=b=>{if(m(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const v=Gn(b);if(v){const k=Hn(v.r,v.g,v.b);d(k.h),i(k.s),u(k.l)}}},N=()=>{/^#[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(${o}, 100%, 50%)`},onClick:g,onMouseMove:b=>{b.buttons===1&&g(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-l}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:b=>f(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=>h(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:N,children:"OK"})]})]})}function Gn(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 rl(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function Hn(s,a,r){s/=255,a/=255,r/=255;const o=Math.max(s,a,r),d=Math.min(s,a,r);let c=0,i=0;const l=(o+d)/2;if(o!==d){const u=o-d;switch(i=l>.5?u/(2-o-d):u/(o+d),o){case s:c=((a-r)/u+(a<r?6:0))/6;break;case a:c=((r-s)/u+2)/6;break;case r:c=((s-a)/u+4)/6;break}}return{h:Math.round(c*360),s:Math.round(i*100),l:Math.round(l*100)}}function ol(s,a,r){s/=360,a/=100,r/=100;let o,d,c;if(a===0)o=d=c=r;else{const i=(x,m,f)=>(f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?x+(m-x)*6*f:f<.5?m:f<.6666666666666666?x+(m-x)*(.6666666666666666-f)*6:x),l=r<.5?r*(1+a):r+a-r*a,u=2*r-l;o=i(u,l,s+1/3),d=i(u,l,s),c=i(u,l,s-1/3)}return{r:Math.round(o*255),g:Math.round(d*255),b:Math.round(c*255)}}const ll=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function il(){var S,A,I,E,w,D,M,F,V,R;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>{var T;return(T=j.card)==null?void 0:T.preferences}),r=Te.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions(),c=y.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:i}=n.useEditorCardQuery(c),[l,u]=y.useState({}),[x,m]=y.useState(null),[f,g]=y.useState(null),p=y.useMemo(()=>{var O,B,z,_,q,G,H;if(!(i!=null&&i.records)||i.records.length===0)return[];const j=r==="stackedBar"||r==="stackedLine",T=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",L=((O=s==null?void 0:s.config)==null?void 0:O.pivotByColumns)&&s.config.pivotByColumns.length>0;if((j||T)&&L){if(i.pivotSchema&&Array.isArray(i.pivotSchema)){const $=new Set;return i.pivotSchema.forEach(W=>{W.alias&&$.add(W.alias)}),Array.from($)}if(i.records.length>0){const $=i.records[0],W=Object.keys($),Q=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(pe=>{Q.add(pe.label||pe.name),Q.add(pe.alias||pe.name)});const se=new Set;return(z=s==null?void 0:s.config)!=null&&z.metricColumns&&s.config.metricColumns.forEach(pe=>{const ge=pe.alias||pe.name;se.add(ge),se.add(`${ge}_count`),se.add(`${ge}_sum`),se.add(`${ge}_avg`),se.add(`${ge}_min`),se.add(`${ge}_max`);const ve=pe.entityName||pe.qualifiedEntityName;ve&&(se.add(`${ve}_${ge}`),se.add(`${ve}_${ge}_count`))}),W.filter(pe=>!Q.has(pe)&&!se.has(pe))}}if((T||j)&&!L&&((q=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&q.length))return s.config.metricColumns.map($=>$.alias||$.label||$.name);if((H=(G=s==null?void 0:s.config)==null?void 0:G.groupByColumns)!=null&&H.length){const $=s.config.groupByColumns[0],W=$.label||$.name,Q=new Set;return i.records.forEach(se=>{const ue=se[W];ue!=null&&Q.add(String(ue))}),Array.from(Q)}return[]},[i,(S=s==null?void 0:s.config)==null?void 0:S.groupByColumns,(A=s==null?void 0:s.config)==null?void 0:A.pivotByColumns,(I=s==null?void 0:s.config)==null?void 0:I.metricColumns,r]),h=y.useMemo(()=>n.getDefaultChartColors(),[]);y.useEffect(()=>{const j={};p.forEach((T,L)=>{j[T]=n.getColorForValue(T,L,a==null?void 0:a.colorConfig)}),u(j)},[p,a==null?void 0:a.colorConfig,h]);const N=(j,T)=>{const L={...l,[j]:T};u(L);const O={...a||{},colorConfig:{segments:L}};o(O);const B={...s,preferences:O};d(B)},b=(j,T)=>{var q;const L=h[T%h.length],{[j]:O,...B}=((q=a==null?void 0:a.colorConfig)==null?void 0:q.segments)||{},z={...a||{},colorConfig:{segments:B}};o(z);const _={...s,preferences:z};d(_),u(G=>({...G,[j]:L}))};if(!p.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((w=(E=s==null?void 0:s.config)==null?void 0:E.groupByColumns)==null?void 0:w.length)||((M=(D=s==null?void 0:s.config)==null?void 0:D.pivotByColumns)==null?void 0:M.length):(V=(F=s==null?void 0:s.config)==null?void 0:F.groupByColumns)==null?void 0:V.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const P=()=>{const j={...a||{},colorConfig:{segments:{}}};o(j);const T={...s,preferences:j};d(T);const L={};p.forEach((O,B)=>{L[O]=n.getColorForValue(O,B,void 0)}),u(L)},C=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(Xa.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:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:P,children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:p.map((j,T)=>{const L=n.isDefaultColor(l[j],T),O=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===j,onOpenChange:B=>m(B?j: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:l[j]}})}),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:h.slice(0,10).map((B,z)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",l[j]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{N(j,B),m(null)},children:[z===T%h.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:B})]},`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:ll.map((B,z)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",l[j]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{N(j,B),m(null)},children:e.jsx("span",{className:"sr-only",children:B})},`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:()=>{g({value:j,color:l[j]}),m(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(j,T),m(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:j}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},j)})}),f&&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:()=>g(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(al,{color:f.color,onColorChange:j=>{N(f.value,j),g(null)},onClose:()=>g(null)})})]})]})})]})}function lt({value:s,onSave:a,placeholder:r="",type:o="text",className:d=""}){const[c,i]=y.useState(s??""),[l,u]=y.useState(!1);y.useEffect(()=>{i(s??"")},[s]);const x=()=>{a(c),u(!1)},m=()=>{i(s??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:l?c:s??"",onChange:f=>{i(f.target.value),u(!0)},onFocus:()=>u(!0),onClick:f=>f.stopPropagation(),className:"h-8 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.stopPropagation(),f.key==="Enter"&&l&&c!==s?x():f.key==="Escape"&&m()},"aria-label":r||"Edit field"}),l&&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:m,children:e.jsx(ae.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function as(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function wa(s,a){if(!a||a==="auto")return{type:"auto"};if(a==="duration")return{type:"duration",multiplyBy:void 0,percentValueMode:void 0,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits};const r={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?Ds(r,as(a)):r}function cl(s){const a=s.type||"auto";return a==="auto"?s:a==="duration"?{type:"duration",prefix:s.prefix,suffix:s.suffix,negativeInParentheses:s.negativeInParentheses,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits}:wa(s,a)}function Ds(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const dl=["auto","number","currency","percent","scientific","date","duration"],ul=[{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"}],ml=[{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"}],Ns=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],xl=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],hl=s=>s.charAt(0).toUpperCase()+s.slice(1);function ls({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:o="NUMBER FORMAT",maxDecimalPlaces:d=10}){const c=s.type||"auto",i=cl(s),l=h=>{h.stopPropagation()},u=(h,N)=>{a({...i,[h]:N})},[x,m]=y.useState(()=>String(i.decimalPlaces??as(c))),[f,g]=y.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),p=h=>{a(wa(s,h))};return y.useEffect(()=>{m(String(i.decimalPlaces??as(c)))},[i.decimalPlaces,c]),y.useEffect(()=>{g(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsxs(t.Select,{value:c,onValueChange:h=>p(h),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:dl.map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h==="auto"?"Auto (Default)":hl(h)},h))})]})]}),c!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(c)&&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:d,placeholder:"0",value:x,onClick:l,onPointerDown:l,onKeyDown:l,onChange:h=>{const N=h.target.value.replace(/[^\d]/g,"");m(N),N!==""&&a(Ds(i,Math.max(0,Math.min(d,parseInt(N,10)))))},onBlur:()=>{if(x!=="")return;const h=as(c);m(String(h)),a(Ds(i,h))},className:"h-8 text-xs"})})]}),c==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:h=>u("currency",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ul.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),["number","currency"].includes(c)&&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:h=>h.stopPropagation(),onCheckedChange:h=>u("useSuffix",h)})]}),c!=="duration"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:h=>u("locale",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ml.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:h=>u("prefix",h.target.value),className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:h=>u("suffix",h.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(c)&&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:h=>h.stopPropagation(),onCheckedChange:h=>u("negativeInParentheses",h)})]}),c==="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:f,onClick:l,onPointerDown:l,onKeyDown:l,onChange:h=>{const N=h.target.value.replace(/[^0-9.]/g,"");g(N),u("multiplyBy",N?parseFloat(N):void 0)},className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:h=>u("dateFormat",h.target.value),className:"h-8 text-xs"})})]}),c==="duration"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Value Is"}),e.jsxs(t.Select,{value:s.durationInputUnit||"second",onValueChange:h=>u("durationInputUnit",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Display"}),e.jsxs(t.Select,{value:s.durationDisplayStyle||"compact",onValueChange:h=>u("durationDisplayStyle",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xl.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Smallest"}),e.jsxs(t.Select,{value:s.durationSmallestUnit||"second",onValueChange:h=>u("durationSmallestUnit",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Largest"}),e.jsxs(t.Select,{value:s.durationLargestUnit||"day",onValueChange:h=>u("durationLargestUnit",h),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(h=>e.jsx(t.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]})]})]})]})}function Cs({axis:s,label:a,type:r,config:o,onChange:d,defaultTitle:c,hidePosition:i}){var h,N,b,v,k,P,C,S,A,I,E,w,D,M;const l=n.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),u=(F,V)=>{d({...o??{},[F]:V})},x=(F,V)=>{var L,O,B,z;const R=F==="enabled"&&V===!0,j=(L=o==null?void 0:o.name)==null?void 0:L.text,T=R&&!j&&c;d({...o??{},name:{...o==null?void 0:o.name,enabled:F==="enabled"?V:((O=o==null?void 0:o.name)==null?void 0:O.enabled)??!1,text:F==="text"?V:T?c:j,fontSize:F==="fontSize"?V:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:F==="fontWeight"?V:(z=o==null?void 0:o.name)==null?void 0:z.fontWeight}})},m=(F,V)=>{var R,j;d({...o??{},labels:{enabled:F==="enabled"?V:((R=o==null?void 0:o.labels)==null?void 0:R.enabled)??!0,rotation:F==="rotation"?V:(j=o==null?void 0:o.labels)==null?void 0:j.rotation}})},f=(F,V)=>{d({...o??{},scale:{...o==null?void 0:o.scale,[F]:V===""?"auto":Number(V)}})},g=s==="x"?["auto","top","bottom"]:["auto","left","right"],p=["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:(o==null?void 0:o.enabled)!==!1,onCheckedChange:F=>u("enabled",F),onClick:F=>F.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:((h=o==null?void 0:o.name)==null?void 0:h.enabled)??!1,onCheckedChange:F=>x("enabled",F===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((N=o==null?void 0:o.name)==null?void 0:N.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(lt,{placeholder:`${a} title`,value:((b=o==null?void 0:o.name)==null?void 0:b.text)||"",onSave:F=>x("text",F),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(lt,{type:"number",placeholder:"12",value:String(((v=o==null?void 0:o.name)==null?void 0:v.fontSize)||12),onSave:F=>x("fontSize",Number(F)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((k=o==null?void 0:o.name)==null?void 0:k.fontWeight)||"normal",onValueChange:F=>x("fontWeight",F),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(o==null?void 0:o.position)||"auto",onValueChange:F=>u("position",F),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:g.map(F=>e.jsx(t.SelectItem,{value:F,className:"text-xs",children:F==="auto"?"Auto (Default)":t.titleCase(F)},F))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((P=o==null?void 0:o.labels)==null?void 0:P.enabled)!==!1,onCheckedChange:F=>m("enabled",F)})]}),((C=o==null?void 0:o.labels)==null?void 0:C.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(((S=o==null?void 0:o.labels)==null?void 0:S.rotation)||"auto"),onValueChange:F=>m("rotation",F==="auto"?"auto":Number(F)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(F=>e.jsx(t.SelectItem,{value:F,className:"text-xs",children:F==="auto"?"Auto (Default)":`${F}°`},F))})]})]})]}),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:l==="override",onCheckedChange:F=>d({...o,formatMode:F?"override":"inherit"})})]}),l==="override"&&e.jsx(ls,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:F=>d({...o,formatMode:"override",formatOptions:F}),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(lt,{type:"number",placeholder:"auto",value:((A=o==null?void 0:o.scale)==null?void 0:A.min)==="auto"||((I=o==null?void 0:o.scale)==null?void 0:I.min)===void 0?"":String(o.scale.min),onSave:F=>f("min",F),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(lt,{type:"number",placeholder:"auto",value:((E=o==null?void 0:o.scale)==null?void 0:E.max)==="auto"||((w=o==null?void 0:o.scale)==null?void 0:w.max)===void 0?"":String(o.scale.max),onSave:F=>f("max",F),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(lt,{type:"number",placeholder:"auto",value:((D=o==null?void 0:o.scale)==null?void 0:D.stepSize)==="auto"||((M=o==null?void 0:o.scale)==null?void 0:M.stepSize)===void 0?"":String(o.scale.stepSize),onSave:F=>f("stepSize",F),className:""})})]})]})]})]})]})}function Ss(s,a,r){var c,i,l;if(s==="x"){const u=(i=(c=a==null?void 0:a.config)==null?void 0:c.groupByColumns)==null?void 0:i[0];return(u==null?void 0:u.label)||(u==null?void 0:u.name)||""}const o=((l=a==null?void 0:a.config)==null?void 0:l.metricColumns)||[],d=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const u=o.filter((x,m)=>{const f=d.find(g=>g.idx===m);return!f||f.yAxisId!=="y2"});return u.length===1&&(u[0].label||u[0].name)||""}if(s==="y2"){const u=o.filter((x,m)=>{const f=d.find(g=>g.idx===m);return(f==null?void 0:f.yAxisId)==="y2"});return u.length===1&&(u[0].label||u[0].name)||""}return""}function pl(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),d=Te.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const c=n.AxisConfigurator.getAxisInfo(d,a);if(!c.hasXAxis&&!c.hasYAxis)return null;const i=(u,x)=>{let m;u==="x"?m="xAxisConfig":u==="y"?m="yAxisConfig":m="secondaryYAxisConfig";const f={...a||{},[m]:x};r(f);const g={...s,preferences:f};o(g)},l=c.hasY2Axis&&d==="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(Cs,{axis:"x",label:"X-Axis",type:c.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"x"),a==null?void 0:a.xAxisConfig),onChange:u=>i("x",u),defaultTitle:Ss("x",s,a)}),c.hasYAxis&&e.jsx(Cs,{axis:"y",label:l?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"y"),a==null?void 0:a.yAxisConfig),onChange:u=>i("y",u),defaultTitle:Ss("y",s,a)}),l&&e.jsx(Cs,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:u=>i("y2",u),defaultTitle:Ss("y2",s,a),hidePosition:!0})]})})]})}function fl(){const s=t.useEditorStore(f=>f.card),a=Te.useEffectiveEditorCardType(),r=t.useEditorStore(f=>{var g,p,h,N;return(N=(h=(p=(g=f.card)==null?void 0:g.preferences)==null?void 0:p.chartOptions)==null?void 0:h.plugins)==null?void 0:N.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const d=n.getDefaultLegendConfig(a),c=(d==null?void 0:d.display)??!0,i=(d==null?void 0:d.position)??"top",l=(d==null?void 0:d.align)??"center",u=(f,g)=>{const p={...r,[f]:g};o(p)},x=["top","bottom","left","right"],m=["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(cr,{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:f=>u("display",f)})]}),((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)||i,onValueChange:f=>u("position",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:t.titleCase(f)},f))})]})]}),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)||l,onValueChange:f=>u("align",f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(f=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:t.titleCase(f)},f))})]})]})]})]})})]})}function gl(){var V,R,j,T,L,O,B;const s=t.useEditorStore(z=>z.card),a=Te.useEffectiveEditorCardType(),r=t.useEditorStore(z=>{var _,q;return(q=(_=z.card)==null?void 0:_.preferences)==null?void 0:q.dataLabelsConfig}),o=t.useEditorStore(z=>{var _;return(_=z.card)==null?void 0:_.preferences}),{setCardPreferences:d,updateCardInFrame:c}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const i=a==="bullet"?((V=o==null?void 0:o.bulletConfig)==null?void 0:V.orientation)??(((R=o==null?void 0:o.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,l=i!=null?i==="horizontal":((j=o==null?void 0:o.chartOptions)==null?void 0:j.indexAxis)==="y",u=a==="stackedBar"||a==="stackedLine",x=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",m=a==="bubble"||a==="scatter",f=(L=(T=o==null?void 0:o.chartOptions)==null?void 0:T.plugins)==null?void 0:L.datalabels,g=(f==null?void 0:f.display)!==!1&&((f==null?void 0:f.anchor)||(f==null?void 0:f.align)),p=n.getDefaultDataLabelsConfig(a,s.preferences),h=r??p,N=(p==null?void 0:p.enabled)??g??!1,b=(r==null?void 0:r.enabled)!==void 0?r.enabled:N,v=(z,_)=>{const H={...p??{},...r??{},[z]:_};z==="enabled"&&(H.display=_,_&&m&&!H.position&&(H.position="bottom")),z==="position"&&m&&(H.position="bottom"),z==="formatMode"&&_==="inherit"&&(H.format=void 0,H.formatOptions=void 0);const $={...s.preferences||{},dataLabelsConfig:H};d($);const W={...s,preferences:$};c(W)},k=(z,_)=>{const q=r??{},H={...p??{},...q,font:{...q.font||{},[z]:_}},$={...s.preferences||{},dataLabelsConfig:H};d($);const W={...s,preferences:$};c(W)},P=()=>{const z=a;return z==="stackedBar"||z==="stackedLine"||z==="pie"||z==="doughnut"?"center":l?"right":"top"},C=a!=="treemap"&&a!=="heatmap",S=a!=="treemap",A=P();let I=[];if(C)if(m)I=["bottom"];else if(u||x)I=["center"];else{const z=l?["center","left","right"]:["center","top","bottom"];I=["auto",...a==="bullet"?z:z.filter(q=>q!==A),"custom"]}const E=()=>t.titleCase(A),w=["center","start","end"],D=["center","start","end","top","bottom"],M=(h==null?void 0:h.formatMode)||(h!=null&&h.format&&!["auto"].includes(h.format)?"override":"inherit"),F=(h==null?void 0:h.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(Nr,{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=>v("enabled",z)})]}),b&&e.jsxs(e.Fragment,{children:[C&&!u&&!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:m?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:z=>v("position",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:I.map(z=>e.jsx(t.SelectItem,{value:z,className:"text-xs",children:z==="auto"?E():z==="custom"?"Custom (Advanced)":t.titleCase(z)},z))})]})]}),u&&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=>v("showTotal",z)})]}),(h==null?void 0:h.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(h==null?void 0:h.anchor)||"center",onValueChange:z=>v("anchor",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:w.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((h==null?void 0:h.align)||"center"),onValueChange:z=>v("align",z),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:D.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:M==="override",onCheckedChange:z=>v("formatMode",z?"override":"inherit")})]}),M==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:F,onCheckedChange:z=>{const _=r??{},G={...p??{},..._,formatMode:"override",format:z?"none":void 0,formatOptions:z?void 0:_.formatOptions},H={...s.preferences||{},dataLabelsConfig:G};d(H),c({...s,preferences:H})}})]}),!F&&e.jsx(ls,{formatOptions:(h==null?void 0:h.formatOptions)||{},onFormatOptionsChange:z=>{const G={...p??{},...r??{},formatMode:"override",format:z.type&&z.type!=="auto"?z.type:void 0,formatOptions:z},H={...s.preferences||{},dataLabelsConfig:G};d(H),c({...s,preferences:H})},showTitle:!1})]})]}),S&&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(lt,{type:"number",placeholder:"12",value:String(((O=h==null?void 0:h.font)==null?void 0:O.size)||12),onSave:z=>k("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:((B=h==null?void 0:h.font)==null?void 0:B.weight)||"normal",onValueChange:z=>k("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:(h==null?void 0:h.color)==="auto"||!(h!=null&&h.color)?"auto":"custom",onValueChange:z=>{z==="auto"&&v("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(lt,{type:"number",placeholder:"0",value:String((h==null?void 0:h.rotation)||0),onSave:z=>v("rotation",Number(z)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function bl(){var c;const s=t.useEditorStore(i=>{var l;return(l=i.card)==null?void 0:l.type}),a=t.useEditorStore(i=>{var l;return(l=i.card)==null?void 0:l.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((c=a==null?void 0:a.chartOptions)==null?void 0:c.treemapColorMode)??"branch",d=i=>{const l={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};r(l)};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:o,onValueChange:i=>d(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(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 jl=Object.keys(n.HEATMAP_PRESET_PALETTES);function vl(){const s=t.useEditorStore(g=>g.card),a=t.useEditorStore(g=>{var p;return(p=g.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",d=(a==null?void 0:a.heatmapConfig)||{},c=d.colorPalette??"green",i=d.legendPosition??"bottom",l=y.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),u=g=>{const p={...d,...g};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:p})},x=g=>{u({colorPalette:g,colorRange:g==="custom"?d.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(g,p)=>{const h=[...l];h[g]=p,u({colorPalette:"custom",colorRange:h})},f=g=>{u({legendPosition:g})};return o?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:g=>x(g??"blue"),className:"space-y-3",children:[jl.map(g=>{const p=n.HEATMAP_PRESET_PALETTES[g];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-${g}`,value:g}),e.jsxs(t.Label,{htmlFor:`heatmap-${g}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},g)}),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-2 pl-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:l[0],onChange:g=>m(0,g??"#000000"),ariaLabel:"Start color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Start color"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:l[1],onChange:g=>m(1,g??"#000000"),ariaLabel:"End color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"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:i,onValueChange:g=>f(g??"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(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:g[0].toUpperCase()+g.slice(1)},g))})]})]})]})]}):null}const Qn=["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 yl(){var V,R;const s=t.useEditorStore(j=>j.card.preferences),a=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.isDevMode),{setCardPreferences:o,setChartOrientation:d}=t.useEditorActions(),c=y.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),l=At.hasValidCardConfig(a==null?void 0:a.config)&&!r,[u,x]=y.useState(c.showRanges??!1),[m,f]=y.useState(c.rangesArePercentages??!1),g=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!l,[p,h]=y.useState(g);y.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),y.useEffect(()=>{f(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const N=c.targetValue===void 0?"":String(c.targetValue);y.useEffect(()=>{const j=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!l;h(j)},[c.disableAutoComparative,c.comparativeMetricKey,l]);const b=y.useMemo(()=>{var j,T;return((T=(j=a==null?void 0:a.config)==null?void 0:j.metricColumns)==null?void 0:T.map(L=>{const O=L.label||L.name||L.alias||"";return{value:O,label:O}}))||[]},[(V=a==null?void 0:a.config)==null?void 0:V.metricColumns]);y.useEffect(()=>{var q,G;if(!s||b.length===0)return;const j={};let T=!1;const L=(q=b[1])==null?void 0:q.value;!c.targetMetricKey&&L&&(j.targetMetricKey=L,T=!0);const O=(G=b[2])==null?void 0:G.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&O&&(j.comparativeMetricKey=O,T=!0);const B=b.slice(3),z={...c.rangeKeys||{}};let _=!1;if(Qn.forEach((H,$)=>{!z[H]&&B[$]&&(z[H]=B[$].value,_=!0)}),_&&(j.rangeKeys=z,T=!0,c.showRanges===void 0&&(j.showRanges=!0)),T){const H=Wn({...c,...j});o({...s,bulletConfig:H})}},[b,c,s,o]);const v=j=>{const T=Wn({...c,...j});o({...s,bulletConfig:T})},k=(j,T)=>{const L={...c.rangeKeys||{},[j]:T.trim()};T.trim()||delete L[j],v({rangeKeys:Object.keys(L).length>0?L:void 0})},P=(j,T)=>{const L=T===""?void 0:Number(T),O={...c.ranges||{}};L===void 0||Number.isNaN(L)?delete O[j]:O[j]=L,v({ranges:Object.keys(O).length?O:void 0})},C=j=>{if(j===""){v({targetValue:void 0});return}const T=Number(j);v({targetValue:Number.isNaN(T)?void 0:T})},S=(j,T)=>{const L=T.trim(),O={...c.rangeLabels||{}};L?O[j]=L:delete O[j],v({rangeLabels:Object.keys(O).length>0?O:void 0})},A=j=>{x(j),v({showRanges:j})},I=j=>{f(j),v({rangesArePercentages:j})},E=c.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),w=j=>{v({orientation:j}),d(j==="horizontal"?"y":"x")},D=[{value:"__none",label:"None"},...b.map(j=>({value:j.value,label:j.label}))],M=D,F=j=>{if(h(j),!j){v({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!l){v({disableAutoComparative:!1});return}if(c.comparativeMetricKey)v({disableAutoComparative:!1});else{const T=b.find(L=>L.value!==c.targetMetricKey);v({comparativeMetricKey:T==null?void 0:T.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:E,onValueChange:j=>w(j),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"})]})]})]}),l&&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:j=>v({targetMetricKey:j==="__none"?void 0:j}),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(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),l?e.jsxs(t.Select,{value:c.comparativeMetricKey||"__none",onValueChange:j=>v({comparativeMetricKey:j==="__none"?void 0:j,disableAutoComparative:j==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:D.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:p,onCheckedChange:j=>F(j)})]}),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(Ze,{type:"number",className:"h-8 text-xs",value:N,onCommit:C,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:u,onCheckedChange:A})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!u,onChange:j=>I(j.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),u&&e.jsx("div",{className:"space-y-3",children:Qn.map(j=>{var T,L,O,B,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:[j," LABEL"]}),e.jsx(Ze,{placeholder:`Display label (${j})`,value:((T=c.rangeLabels)==null?void 0:T[j])||"",onCommit:_=>S(j,_),className:"h-8 text-xs"})]}),l?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[j," COLUMN"]}),e.jsxs(t.Select,{value:((L=c.rangeKeys)==null?void 0:L[j])||"__none",onValueChange:_=>{_==="__none"?k(j,""):k(j,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:M.map(_=>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:[j," COLUMN KEY"]}),e.jsx(Ze,{placeholder:"Column key",value:((O=c.rangeKeys)==null?void 0:O[j])||"",onCommit:_=>k(j,_),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:[j," VALUE"]}),e.jsx(Ze,{type:"number",placeholder:m?"0.80":"Static value",value:((B=c.ranges)==null?void 0:B[j])===void 0?"":String((z=c.ranges)==null?void 0:z[j]),onCommit:_=>P(j,_),className:"h-8 text-xs"})]})]},j)})})]})]})]})}function Yn(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 Nl(){var S,A,I,E,w,D,M,F,V,R,j,T;const s=t.useEditorStore(L=>L.card.preferences),a=t.useEditorStore(L=>L.card),r=Te.useEffectiveEditorCardType(),o=t.useEditorStore(L=>L.isDevMode),{setCardPreferences:d,updateCardInFrame:c}=t.useEditorActions(),i=r==="bubble",l=r==="scatter",u=y.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),m=At.hasValidCardConfig(a==null?void 0:a.config)&&!o,f=y.useMemo(()=>{var L,O;return((O=(L=a==null?void 0:a.config)==null?void 0:L.metricColumns)==null?void 0:O.map(B=>{const z=B.label||B.name||B.alias||"";return{value:z,label:z}}))||[]},[(S=a==null?void 0:a.config)==null?void 0:S.metricColumns]),g=y.useMemo(()=>{var L,O;return((O=(L=a==null?void 0:a.config)==null?void 0:L.groupByColumns)==null?void 0:O.map(B=>{const z=B.label||B.name||B.alias||"";return{value:z,label:z}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.groupByColumns]),p=y.useMemo(()=>u.enableGrouping!==void 0?u.enableGrouping:!o&&g.length>=2,[u.enableGrouping,o,g.length]),[h,N]=y.useState(p);y.useEffect(()=>{N(p)},[p]);const b=L=>{const O={...s||{},bubbleScatterConfig:L};d(O),a&&c({...a,preferences:O})},v=L=>{d(L),a&&c({...a,preferences:L})};y.useEffect(()=>{if(!s||f.length===0)return;const L={};let O=!1;if(!u.xMetricKey&&f[0]&&(L.xMetricKey=f[0].value,O=!0),!u.yMetricKey&&f[1]&&(L.yMetricKey=f[1].value,O=!0),i&&!u.radiusMetricKey&&f[2]&&(L.radiusMetricKey=f[2].value,O=!0),!u.labelKey&&g[0]&&(L.labelKey=g[0].value,O=!0),p&&!u.groupKey&&g[1]&&(L.groupKey=g[1].value,L.enableGrouping=!0,O=!0),O){const B=Yn({...u,...L});b(B)}},[f,g,u,s,d,i,p]);const k=L=>{const O=Yn({...u,...L});b(O)},P=L=>{N(L),k({enableGrouping:L,groupKey:L?u.groupKey:void 0})};if(!i&&!l)return null;const C=i?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(C,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[i?"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"}),m?e.jsxs(t.Select,{value:u.labelKey||"",onValueChange:L=>k({labelKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:g.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ze,{className:"h-8 text-xs",placeholder:"Column name for labels",value:u.labelKey||"",onCommit:L=>k({labelKey:L})})]}),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:h,onCheckedChange:P})]}),h&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),m?e.jsxs(t.Select,{value:u.groupKey||"",onValueChange:L=>k({groupKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:g.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ze,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:u.groupKey||"",onCommit:L=>k({groupKey:L})})]})]}),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"}),m?e.jsxs(t.Select,{value:u.xMetricKey||"",onValueChange:L=>k({xMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:f.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ze,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:u.xMetricKey||"",onCommit:L=>k({xMetricKey:L})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),m?e.jsxs(t.Select,{value:u.yMetricKey||"",onValueChange:L=>k({yMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:f.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ze,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:u.yMetricKey||"",onCommit:L=>k({yMetricKey:L})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),m?e.jsxs(t.Select,{value:u.radiusMetricKey||"",onValueChange:L=>k({radiusMetricKey:L}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:f.map(L=>e.jsx(t.SelectItem,{value:L.value,children:L.label},L.value))})]}):e.jsx(Ze,{className:"h-8 text-xs",placeholder:"Column name for radius",value:u.radiusMetricKey||"",onCommit:L=>k({radiusMetricKey:L})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:u.radiusScale||"sqrt",onValueChange:L=>k({radiusScale:L}),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"})]})]})]}),u.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(Ze,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((I=u.minRadius)==null?void 0:I.toString())||"",onCommit:L=>k({minRadius:L?Number(L):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Ze,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((E=u.maxRadius)==null?void 0:E.toString())||"",onCommit:L=>k({maxRadius:L?Number(L):void 0})})]})]}),u.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",u.fixedRadius||10]}),e.jsx(n.Slider,{value:[u.fixedRadius||10],onValueChange:([L])=>k({fixedRadius:L}),min:3,max:30,step:1,className:"py-2"})]})]}),l&&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: ",u.fixedRadius||5]}),e.jsx(n.Slider,{value:[u.fixedRadius||5],onValueChange:([L])=>k({fixedRadius:L}),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:((D=(w=s==null?void 0:s.xAxisConfig)==null?void 0:w.name)==null?void 0:D.enabled)??!1,onCheckedChange:L=>{var z,_,q,G;const O=u.xMetricKey||"X Axis",B=u.yMetricKey||"Y Axis";v({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:L,text:((_=(z=s==null?void 0:s.xAxisConfig)==null?void 0:z.name)==null?void 0:_.text)||O}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:L,text:((G=(q=s==null?void 0:s.yAxisConfig)==null?void 0:q.name)==null?void 0:G.text)||B}}})}})]}),((F=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:F.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx(Ze,{className:"h-8 text-xs",placeholder:u.xMetricKey||"X Axis",value:((R=(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name)==null?void 0:R.text)||"",onCommit:L=>{var O;v({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(O=s==null?void 0:s.xAxisConfig)==null?void 0:O.name,enabled:!0,text:L||u.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Ze,{className:"h-8 text-xs",placeholder:u.yMetricKey||"Y Axis",value:((T=(j=s==null?void 0:s.yAxisConfig)==null?void 0:j.name)==null?void 0:T.text)||"",onCommit:L=>{var O;v({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(O=s==null?void 0:s.yAxisConfig)==null?void 0:O.name,enabled:!0,text:L||u.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Cl=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Sl(){const s=t.useEditorStore(g=>g.card),a=t.useEditorStore(g=>{var p;return(p=g.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",d=(a==null?void 0:a.funnelConfig)||{},c=d.percentMode??"percentOfTotal",i=d.shrinkFraction??1,l=d.labelThreshold??0,u=g=>{const p={...d,...g};r({...a||{},funnelConfig:p})},x=g=>{u({percentMode:g})},m=g=>{u({shrinkFraction:g[0]})},f=g=>{u({labelThreshold:g[0]})};return o?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:g=>x(g),className:"space-y-2",children:Cl.map(g=>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-${g.value}`,value:g.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${g.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]})]},g.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:[i],onValueChange:m,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:[l],onValueChange:f,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:l===0?"Showing all labels":`Hide labels below ${l}%`})]})]})]}):null}function is(){const s=t.useEditorStore(i=>i.card),{data:a,comparisonMetadata:r}=n.useEditorCardQuery(s),{keys:o}=n.getKeys((a==null?void 0:a.records)||[],r),d=o.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let c=d;if(["stackedBar","stackedLine"].includes(s.type)){const i=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:o[0],pivotKey:o[1],valueKey:o[2]}),{keys:l}=n.getKeys(i);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:o.slice(0,1),keys:o,defaultMetricKeys:d}}const wl=[{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"}],Tl=[{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)"}],El=["center","start","end"],Il=["center","start","end","top","bottom"];function cs({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:d,showAppearance:c=!0}){var h,N,b,v,k,P;const i=d??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),l=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],u=(C,S)=>{const A={...s,[C]:S};a(A)},x=(C,S)=>{const A={...s,font:{...(s==null?void 0:s.font)||{},[C]:S}};a(A)},m=(C,S)=>{const A={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:S}};a(A)},f=()=>r?"Right":"Top",g=s||{},p=g.format||(o?"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:g.position||"auto",onValueChange:C=>u("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?f():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),g.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:g.anchor||"center",onValueChange:C=>u("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),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(g.align||"center"),onValueChange:C=>u("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Il.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),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:p,onValueChange:C=>u("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&o?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(p)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(p)&&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(lt,{type:"number",placeholder:"0",value:String(((h=g.formatOptions)==null?void 0:h.decimalPlaces)??(p==="currency"?2:p==="percent"?1:0)),onSave:C=>m("decimalPlaces",Number(C)),className:""})})]}),p==="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:((N=g.formatOptions)==null?void 0:N.currency)||"USD",onValueChange:C=>m("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(p)&&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=g.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:C=>m("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((v=g.formatOptions)==null?void 0:v.locale)||"en-US",onValueChange:C=>m("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.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(lt,{type:"number",placeholder:"12",value:String(((k=g.font)==null?void 0:k.size)||12),onSave:C=>x("size",Number(C)),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:((P=g.font)==null?void 0:P.weight)||"normal",onValueChange:C=>x("weight",C),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:g.color==="auto"||!g.color?"auto":"custom",onValueChange:C=>{C==="auto"&&u("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(lt,{type:"number",placeholder:"0",value:String(g.rotation||0),onSave:C=>u("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const kl=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Dl=[0,1,2,3,4,5,6,8,10],Al=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Ll=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ml(){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(Rl,{})})]})}function Rl(){const{transformedMetricKeys:s}=is();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(Fl,{metricKey:a,idx:r},a))})}function Fl({metricKey:s,idx:a}){var v;const[r,o]=y.useState(!1),d=t.useEditorStore(k=>{var P;return(P=k.card)==null?void 0:P.preferences}),c=t.useEditorStore(k=>{var P,C;return(C=(P=k.card)==null?void 0:P.preferences)==null?void 0:C.datasetOptions}),i=c==null?void 0:c.find(k=>k.idx===a),{setCardPreferences:l}=t.useEditorStore(k=>k.actions),u=(i==null?void 0:i.type)||"bar",x=(i==null?void 0:i.yAxisId)||"y",m=((v=i==null?void 0:i.dataLabels)==null?void 0:v.enabled)??!1,f=u==="line"?n.ChartLine:n.ChartColumnIncreasing;function g(k){const P={idx:a,type:u,yAxisId:x,dataLabels:i==null?void 0:i.dataLabels,...k};if(!i)l({...d||{},datasetOptions:[...c||[],P]});else{const C=c==null?void 0:c.map(S=>S.idx===a?{...S,...P}:S);l({...d||{},datasetOptions:C})}}function p(k){g({type:k})}function h(k){g({yAxisId:k})}function N(k){g({dataLabels:{...i==null?void 0:i.dataLabels,enabled:k}})}function b(k){g({dataLabels:k})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,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(Ue.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(f,{className:"h-3 w-3"}),u==="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:kl.map(({type:k,icon:P,label:C})=>{const S=u===k;return e.jsxs("button",{onClick:()=>p(k),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",S?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(P,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:C})]},k)})})]}),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:k=>h(k),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)"})]})]})]})]}),u==="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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:k=>g({lineStyle:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(({value:k,label:P})=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:P},k))})]})]}),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((i==null?void 0:i.pointRadius)??3),onValueChange:k=>g({pointRadius:Number(k)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Dl.map(k=>e.jsx(t.SelectItem,{value:String(k),className:"text-xs",children:k===0?"None":k},k))})]})]}),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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:k=>g({pointStyle:k}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Al.map(({value:k,label:P})=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:P},k))})]})]})]})]}),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:m,onCheckedChange:N})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(cs,{config:i==null?void 0:i.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ws=[{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"}],Ol=[0,1,2,3,4,5,6,8,10],Pl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Vl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Bl(s){return s==null?"origin":s===!1?"false":s}function _l(){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(zl,{})})]})}function zl(){const{transformedMetricKeys:s}=is();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(ql,{metricKey:a,idx:r},a))})}function ql({metricKey:s,idx:a}){var N;const[r,o]=y.useState(!1),d=t.useEditorStore(b=>{var v;return(v=b.card)==null?void 0:v.preferences}),c=t.useEditorStore(b=>{var v,k;return(k=(v=b.card)==null?void 0:v.preferences)==null?void 0:k.datasetOptions}),i=c==null?void 0:c.find(b=>b.idx===a),{setCardPreferences:l}=t.useEditorStore(b=>b.actions),u=Bl(i==null?void 0:i.fill),x=((N=i==null?void 0:i.dataLabels)==null?void 0:N.enabled)??!1,m=ws.find(b=>b.value===u)||ws[0];function f(b){const v={idx:a,fill:u,dataLabels:i==null?void 0:i.dataLabels,...b};if(!i)l({...d||{},datasetOptions:[...c||[],v]});else{const k=c==null?void 0:c.map(P=>P.idx===a?{...P,...v}:P);l({...d||{},datasetOptions:k})}}function g(b){f({fill:b==="false"?!1:b})}function p(b){f({dataLabels:{...i==null?void 0:i.dataLabels,enabled:b}})}function h(b){f({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,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(Ue.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"}),m.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:u,onValueChange:b=>g(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ws.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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:b=>f({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Vl.map(({value:b,label:v})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:v},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((i==null?void 0:i.pointRadius)??3),onValueChange:b=>f({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:Ol.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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:b=>f({pointStyle:b}),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:b,label:v})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:v},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:p})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(cs,{config:i==null?void 0:i.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const $l=[0,1,2,3,4,5,6,8,10],Kl=[{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 │"}],Ts=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ul(){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(Gl,{})})]})}function Gl(){const{transformedMetricKeys:s}=is();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 b;const[r,o]=y.useState(!1),d=t.useEditorStore(v=>{var k;return(k=v.card)==null?void 0:k.preferences}),c=t.useEditorStore(v=>{var k,P;return(P=(k=v.card)==null?void 0:k.preferences)==null?void 0:P.datasetOptions}),i=c==null?void 0:c.find(v=>v.idx===a),{setCardPreferences:l}=t.useEditorStore(v=>v.actions),u=(i==null?void 0:i.lineStyle)||"solid",x=(i==null?void 0:i.pointRadius)??3,m=(i==null?void 0:i.pointStyle)||"circle",f=((b=i==null?void 0:i.dataLabels)==null?void 0:b.enabled)??!1,g=Ts.find(v=>v.value===u)||Ts[0];function p(v){const k={idx:a,lineStyle:u,pointRadius:x,pointStyle:m,dataLabels:i==null?void 0:i.dataLabels,...v};if(!i)l({...d||{},datasetOptions:[...c||[],k]});else{const P=c==null?void 0:c.map(C=>C.idx===a?{...C,...k}:C);l({...d||{},datasetOptions:P})}}function h(v){p({dataLabels:{...i==null?void 0:i.dataLabels,enabled:v}})}function N(v){p({dataLabels:v})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,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(Ue.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(Cr,{className:"h-3 w-3"}),g.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:u,onValueChange:v=>p({lineStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ts.map(({value:v,label:k})=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:k},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(x),onValueChange:v=>p({pointRadius:Number(v)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(v=>e.jsx(t.SelectItem,{value:String(v),className:"text-xs",children:v===0?"None":v},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:m,onValueChange:v=>p({pointStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kl.map(({value:v,label:k})=>e.jsx(t.SelectItem,{value:v,className:"text-xs",children:k},v))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:f,onCheckedChange:h})]}),f&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(cs,{config:i==null?void 0:i.dataLabels,onChange:N,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ql=[0,2,4,6,8,10,12,16,20];function Wl(){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(Yl,{})})]})}function Yl(){const{transformedMetricKeys:s}=is();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(Jl,{metricKey:a,idx:r},a))})}function Jl({metricKey:s,idx:a}){var h;const[r,o]=y.useState(!1),d=t.useEditorStore(N=>{var b;return(b=N.card)==null?void 0:b.type}),c=t.useEditorStore(N=>{var b;return(b=N.card)==null?void 0:b.preferences}),i=t.useEditorStore(N=>{var b,v;return(v=(b=N.card)==null?void 0:b.preferences)==null?void 0:v.datasetOptions}),l=i==null?void 0:i.find(N=>N.idx===a),{setCardPreferences:u}=t.useEditorStore(N=>N.actions),x=(l==null?void 0:l.borderRadius)??0,m=((h=l==null?void 0:l.dataLabels)==null?void 0:h.enabled)??!1;function f(N){const b={idx:a,borderRadius:x,dataLabels:l==null?void 0:l.dataLabels,...N};if(!l)u({...c||{},datasetOptions:[...i||[],b]});else{const v=i==null?void 0:i.map(k=>k.idx===a?{...k,...b}:k);u({...c||{},datasetOptions:v})}}function g(N){f({dataLabels:{...l==null?void 0:l.dataLabels,enabled:N}})}function p(N){f({dataLabels:N})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,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(Ue.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:N=>f({borderRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":`${N}px`},N))})]})]})})]}),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:m,onCheckedChange:g})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(cs,{config:l==null?void 0:l.dataLabels,onChange:p,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Xl=[0,1,2,3,4,5,6,8,10],Zl=[{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 │"}],ei=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ti(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=Te.useEffectiveEditorCardType(),o=a==null?void 0:a.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:c}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const i=(l,u)=>{const x={...a||{},lineStyleConfig:{...o,[l]:u}};d(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(br,{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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:l=>i("lineStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ei.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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((o==null?void 0:o.pointRadius)??3),onValueChange:l=>i("pointRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":l},l))})]})]}),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:(o==null?void 0:o.pointStyle)||"circle",onValueChange:l=>i("pointStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Zl.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}const si=[0,2,4,6,8,10,12,16,20],ni=[{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%"}],ai=[{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 ri(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=Te.useEffectiveEditorCardType(),o=a==null?void 0:a.barStyleConfig,{setCardPreferences:d,updateCardInFrame:c}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const i=(l,u)=>{const x={...a||{},barStyleConfig:{...o,[l]:u}};d(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((o==null?void 0:o.borderRadius)??0),onValueChange:l=>i("borderRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:si.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":`${l}px`},l))})]})]}),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((o==null?void 0:o.barPercentage)??.9),onValueChange:l=>i("barPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ni.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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((o==null?void 0:o.categoryPercentage)??.8),onValueChange:l=>i("categoryPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ai.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}function oi(){const s=t.useEditorStore(r=>{var o,d;return(d=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:d.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(ea,{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(gt,{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 li=["kpi"],Es=2;function yt(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 ii(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 ci(s){return{...s,role:"groupby"}}function di(){var k,P;const s=t.useEditorStore(C=>C.card),a=t.useEditorStore(C=>C.actions.updateCardConfig),r=Te.useEffectiveEditorCardType(),{scopedFields:o}=n.useScopedFields(),d=((k=s.config)==null?void 0:k.metricColumns)||[],c=((P=s.config)==null?void 0:P.summary)||{},i=c.breakdownDimensions||[],l=i.length>0,u=li.includes(r),x=d.length>0,m=c.enabled===!0,f=u&&x,g=Array.from(new Map(o.filter(ii).map(C=>[yt(C),ci(C)])).values()),p=new Set(g.map(C=>yt(C))),h=new Set(i.map(C=>yt(C)).filter(C=>C&&p.has(C)));if(!u)return null;const N=C=>{a(s.id,{summary:{...c,...C}})},b=(C,S)=>{const A=yt(C),I=g.filter(w=>h.has(yt(w))),E=S?h.has(A)?I:[...I,C].slice(0,Es):I.filter(w=>yt(w)!==A);N({breakdownDimensions:E,...E.length>0?{showOnCard:!0}:{}})},v=C=>{if(!C){N({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}N({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:[e.jsxs("div",{className:"flex flex-1 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.jsx(t.Switch,{size:"xs",checked:m,disabled:!f,onClick:C=>C.stopPropagation(),onPointerDown:C=>C.stopPropagation(),onCheckedChange:v,"aria-label":"Enable summary"})]}),e.jsx(n.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!m&&"opacity-60"),children:[!f&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:x?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!m,onCheckedChange:C=>N({showOnCard:C===!0})}),e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"cursor-pointer text-xs",children:"Show summary on card"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:C=>N({includeInDashboardSummary:C===!0})}),e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"cursor-pointer text-xs",children:"Include in dashboard summary"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[i.length,"/",Es]})]}),g.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("ul",{className:"max-h-40 space-y-1 overflow-y-auto",children:g.map(C=>{const S=yt(C),A=h.has(S),I=h.size>=Es,E=!m||!A&&I;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${S}`,checked:A,disabled:E,onCheckedChange:w=>b(C,w===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${S}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},S)})})]})]})})]})}const ui=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function mi(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=Te.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions();if(!s||!ui.has(r||""))return null;const c=a==null?void 0:a.tooltipConfig,i=(c==null?void 0:c.formatMode)||(c==null?void 0:c.mode)||"inherit",l=u=>{const x={...a||{},tooltipConfig:{...c||{},...u}};o(x),d({...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:i==="override",onCheckedChange:u=>l({formatMode:u?"override":"inherit",mode:u?"override":"inherit"})})]}),i==="override"&&e.jsx(ls,{formatOptions:(c==null?void 0:c.formatOptions)||{},onFormatOptionsChange:u=>l({formatMode:"override",mode:"override",formatOptions:u}),showTitle:!1})]})]})}function Ta({mode:s}){const a=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return t.isTableChartType(a)?null:e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Ml,{}),(a==="area"||a==="stackedArea")&&e.jsx(_l,{}),a==="line"&&e.jsx(Ul,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(Wl,{}),e.jsx(ti,{}),e.jsx(ri,{}),e.jsx(bl,{}),s==="config"&&e.jsx(tl,{}),s==="config"&&e.jsx(di,{}),e.jsx(vl,{}),a==="bullet"&&e.jsx(yl,{}),a==="funnel"&&e.jsx(Sl,{}),(a==="bubble"||a==="scatter")&&e.jsx(Nl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(oi,{}),e.jsx(il,{}),e.jsx(pl,{}),e.jsx(fl,{}),e.jsx(gl,{}),e.jsx(mi,{})]})}function xi(){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(Ps,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Ta,{mode:"dev"})})]}):null}function hi({focusSection:s,focusRequestId:a}){const r=t.useEditorStore(i=>i.card),o=r.type;if(t.getVisualizationMode(r)==="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 c(){if(t.supportsRegularTableSettings(o))return e.jsx(Sa,{cardType:o,focusSection:s,focusRequestId:a});switch(o){case"kpi":return e.jsx(Ho,{});case"map":return e.jsx(Xo,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(ya,{})});case"text":return e.jsx(nl,{});default:return e.jsx(xi,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[c(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function pi(){const s=y.useRef(null),a=y.useRef(null),r=t.useEditorStore(v=>v.isShowingVisual),o=t.useEditorStore(v=>v.isDevMode),d=t.useEditorStore(v=>v.showAIDialog),[c,i]=y.useState(!1),[l,u]=y.useState({section:null,id:0}),x=r&&!d,m=x&&(!o||c),f=o&&x,g=()=>i(v=>!v),p=v=>{v&&u(k=>({section:v,id:k.id+1})),o&&i(!0)};y.useEffect(()=>{var v,k,P,C;d?((v=s.current)==null||v.resize(0),(k=a.current)==null||k.resize(0)):((P=s.current)==null||P.resize(25),(C=a.current)==null||C.resize(25))},[d]);const[h,N]=y.useState(!1),b=x?{show:f,isOpen:m,onToggle:g,onOpen:p}: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(no,{})}),e.jsx(vs,{mode:"toolbar",visualAsideControl:b,isDynamicInspectorOpen:h,onDynamicInspectorOpenChange:N})]})}),e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:m?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(vs,{mode:"canvas",visualAsideControl:b,isDynamicInspectorOpen:h,onDynamicInspectorOpenChange:N})}),!d&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(hi,{focusSection:l.section,focusRequestId:l.id})})]}):e.jsx(vs,{mode:"canvas",visualAsideControl:b,isDynamicInspectorOpen:h,onDynamicInspectorOpenChange:N})})]})}function fi(s){var ie;t.useAIInteractionStore(K=>K.currentAIContext);const[a,r]=y.useState(""),[o,d]=y.useState(null),{authToken:c,tokenProps:i}=n.useSemaphorContext(),l=t.useEditorStore(K=>K.card.id),u=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.sql}),x=t.useEditorStore(K=>K.isDevMode),m=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.python}),{setCardPython:f,setCardSql:g,setRunSql:p,switchCardType:h,setQueryConfig:N}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],v=t.useEditorStore(K=>K.userInputForAI),k=t.useEditorStore(K=>K.triggerAIRun),P=t.useEditorStore(K=>K.card),C=t.useEditorStore(K=>K.selectedDatabaseName),S=t.useEditorStore(K=>K.selectedTableName),A=t.useEditorStore(K=>K.selectedConnectionId),I=t.useEditorStore(K=>K.selectedSchemaName),E=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:w,refetch:D,data:M}=n.useEditorCardQuery(P),{setTriggerAIRun:F,setCurrentAssitantScope:V,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:j,connectionType:T,selectedDatamodelId:L}=n.useEditorAside(),O=(ie=n.useDashboardQuery().data)==null?void 0:ie.assistantProfileId,B=y.useRef(n.createAssistantConversationId()),z=y.useRef(null),_=y.useRef(l),q=y.useRef(!1),G=()=>{const K=z.current;K&&(z.current=null,B.current=n.createAssistantConversationId(),K==="clear"&&$([]))},{messages:H,setMessages:$,regenerate:W,error:Q,sendMessage:se,status:ue,addToolResult:pe,stop:ge,clearError:ve}=n.useChat({transport:new n.DefaultChatTransport({api:`${i.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:O,conversationId:B.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:x,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var le;if(q.current=!1,K.name==="AbortError"||(le=K.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),G();return}console.error("[Editor Assistant] Stream error:",K),G()},onToolCall:xe,onFinish({isAbort:K,isDisconnect:le,isError:me}){q.current=!1,r(""),console.log(K?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":me?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),G()}}),Pe=y.useCallback(K=>{q.current=!0;try{const le=se(K);return n.isPromiseLike(le)?le.catch(me=>{throw q.current=!1,me}):le}catch(le){throw q.current=!1,le}},[se]),Ve=y.useCallback(()=>{q.current=!0;try{const K=W();return n.isPromiseLike(K)?K.catch(le=>{throw q.current=!1,le}):K}catch(K){throw q.current=!1,K}},[W]),ee=K=>{let le=!1;$(me=>{const te=typeof K=="function"?K(me):K;if(te.length===0){if(q.current)return z.current="clear",le=!0,me;z.current=null,B.current=n.createAssistantConversationId()}return te}),le&&ge()};y.useEffect(()=>{if(_.current!==l){if(_.current=l,q.current){z.current!=="clear"&&(z.current="rotate"),ge();return}z.current=null,B.current=n.createAssistantConversationId()}},[l,ge]),y.useEffect(()=>{k&&v&&(Pe({role:"user",parts:[{type:"text",text:v}]}),F(!1))},[k,v,Pe,F]);async function xe({toolCall:K}){var le,me,te,de,Le,Me,Qe,re,je,Ce,ne,Ie,ke,Be,We,Se;if(["createChartFromSql","createForecast"].includes(K.toolName)){const De=((le=K.input)==null?void 0:le.sql)??((me=K.args)==null?void 0:me.sql),et=((te=K.input)==null?void 0:te.python)??((de=K.args)==null?void 0:de.python),Fe=((Le=K.input)==null?void 0:Le.chartType)??((Me=K.args)==null?void 0:Me.chartType);h(Fe),g(De),f(et),p(!0),pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!u){pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:u,python:m||""}})}else if(K.toolName==="generateQueryConfig"){r("Generating query config...");const De=((Qe=K.input)==null?void 0:Qe.chartType)??((re=K.args)==null?void 0:re.chartType),et=((je=K.input)==null?void 0:je.queryConfig)??((Ce=K.args)==null?void 0:Ce.queryConfig);((ne=K.input)==null?void 0:ne.cardConfig)??((Ie=K.args)==null||Ie.cardConfig),h(De),R(et),g(void 0),f(void 0);const Fe=await D();if((ke=Fe==null?void 0:Fe.data)!=null&&ke.error){pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:et,message:(Be=Fe==null?void 0:Fe.data)==null?void 0:Be.error.message}});return}if((We=Fe==null?void 0:Fe.data)!=null&&We.records){pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:et,message:"The data has been visualized"}});return}pe({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:et,message:"The data has been visualized",records:(Se=Fe==null?void 0:Fe.data)==null?void 0:Se.records}})}else r("Analyzing...")}function Ee(K){const le=n.removeFromScopeArray(b,K);qe(le)}function qe(K){const le=n.sanitizeAIScope(K);V(le),$(me=>[...me,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(le)}`}]}])}function $e(){const K={databaseName:C||"",schemaName:I||"",tableName:S||"",datamodelId:L||"",datamodelName:t.resolveDatamodelName(j),connectionId:A||"",connectionType:T||""},le=n.dedup([...b,K]);qe(le)}function ce(){const K={databaseName:C||"",schemaName:I||"",tableName:S||"",datamodelName:t.resolveDatamodelName(j),connectionId:A||"",connectionType:T||"",datamodelId:L||""};if(!n.isInAiScopeArray([...E||[],...b],K)||b.length===0){const me=n.dedup([...E||[],...b,K]).filter(te=>te.connectionId===K.connectionId);qe(me)}}const Re=!["ready","error"].includes(ue),we=n.getErrorMessage(Q);return{messages:H,setMessages:ee,sendMessage:Pe,regenerate:Ve,isLoading:Re,handleSetAIScope:ce,handleAddCurrentTableToScope:$e,removeFromCurrentSelections:Ee,currentAssitantScope:b,setCurrentAssitantScope:V,stop:ge,status:ue,toolStatus:a,llmUsage:o,onFinish:s,errorMessage:we,clearError:ve}}const gi=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Jn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const o=y.useRef(null),d=y.useRef(!1),[c,i]=y.useState(!1),[l,u]=y.useState(t.isDevEnv),[x,m]=y.useState(!1),[f,g]=y.useState(!1),[p,h]=y.useState(!1),[N,b]=y.useState(0),v=s??p,k=t.useCurrentAIContext(),{setCurrentAIContext:P,setHasEditorEntitySelectionOverride:C}=t.useAIActions(),{clearQueue:S}=t.useQueueActions(),{clearFileAttachments:A}=t.useFileActions(),I=t.useFileAttachments("editor"),{selectedEntities:E}=n.useAssistantContextEntities("editor"),w=t.useEditorStore(te=>te.card.id),D=t.useEditorStore(te=>te.card.dataSource),M=t.useEditorStore(te=>{var de;return(de=te.card.dataSource)==null?void 0:de.selectedEntities}),F=t.useEditorStore(te=>te.actions.setCardSql),V=t.useEditorStore(te=>te.actions.setRunSql),R=t.useEditorStore(te=>te.showAIDialog),j=t.useDashboardStore(te=>te.handleOpenAssistantProfile),{setShowAIDialog:T,setCardPython:L}=t.useEditorActions(),{assistantProfile:O}=n.useAssistantProfile(),{messages:B,setMessages:z,sendMessage:_,isLoading:q,stop:G,status:H,llmUsage:$,errorMessage:W,clearError:Q}=fi(),[se,ue]=y.useState(""),pe=te=>{ue(te.target.value)},ge=te=>{te.preventDefault();const de=se.trim();if(!de&&I.length===0)return;const Le=[];de&&Le.push({type:"text",text:de}),I.forEach(Me=>{Me.data&&Le.push({type:"file",mediaType:Me.type,filename:Me.name,url:`data:${Me.type};base64,${Me.data}`})}),_({role:"user",parts:Le}),ue(""),A("editor"),ve()},ve=y.useCallback(()=>{b(te=>te+1)},[]);y.useEffect(()=>{var te;R&&!d.current&&((te=o.current)==null||te.focus()),d.current=R},[R]),y.useEffect(()=>{R&&(C(!1),P({selectedEntities:M||[]}))},[w,M,P,C,R]),n.useAutoSubmitQueue({assistantType:"editor",status:H,isLoading:q,sendMessage:_});const{hasActiveTools:Pe,activeToolText:Ve}=n.useActiveToolStatus(B),ee=y.useCallback(te=>{a==null||a(te),s===void 0&&h(te)},[s,a]);y.useEffect(()=>{if(!v)return;function te(de){de.key==="Escape"&&ee(!1)}return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[v,ee]);const xe=y.useCallback(te=>{_({role:"user",parts:[{type:"text",text:te}]}),ve()},[ve,_]),Ee=y.useCallback(async()=>{const te=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(te),n.ue.success("Conversation copied")}catch(de){console.error("Failed to copy conversation",de),n.ue.error("Unable to copy conversation")}},[B]),qe=y.useCallback(()=>{ee(!v)},[v,ee]);function $e(te,de){de==="sql"?(F(te),V(!0)):de==="python"&&(L(te),V(!0))}function ce(){k.selectedEntities.length===0&&P({selectedEntities:E})}function Re(te){ce();const de={role:"user",parts:[{type:"text",text:te.title+" "+te.subtitle}]};_(de),ve()}function we(te){ce(),_({role:"user",parts:[{type:"text",text:te}]}),ve()}function ie(){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:i,children:"Token Usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"Tool Invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:m,children:"System Message"})]})]})}function K(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const le=(se==null?void 0:se.length)===0&&(B==null?void 0:B.filter(te=>te.role==="user").length)===0,me=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",v&&"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:[K(),j&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(O==null?void 0:O.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[ie(),l&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ee,children:"Copy Conversation"}),e.jsx(n.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:qe,children:v?e.jsx(Ue.Minimize2,{className:"size-4"}):e.jsx(Ue.Maximize2,{className:"size-4"})}),e.jsx(n.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{z([]),S("editor"),Q()},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:()=>{T(!1)},children:e.jsx(ae.X,{className:"size-4"})})]})]}),e.jsx(n.AssistantVirtualizedMessages,{messages:B,showTools:l,handleRun:$e,showSystemMessage:x,onQuickReply:xe,disableQuickReplies:q,status:H,errorMessage:W,activeToolText:q&&Pe?Ve:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:R?"bottom-24 right-8":"hidden",scrollToEndSignal:N}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[le&&!O&&e.jsx(n.Placeholders,{onClick:Re,placeholders:gi}),e.jsx("div",{children:le&&O&&e.jsx(n.SeedQuestions,{seedQuestions:O.seedQuestions||[],handleSeedQuestionClick:we})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:o,setInput:ue,stop:G,input:se,handleInputChange:pe,handleSubmit:te=>{ce(),ge(te)},isLoading:q,status:H,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:E,open:f,onOpenChange:g,dataSource:D||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:te=>{C(!0),P({...k,selectedEntities:te})}})]});return v&&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:me})}),r):me}function Ea(s,a,r){if(!a)return!1;const o=a.qualifiedFieldName,d=a.qualifiedEntityName,c=d&&a.name?`${d}.${a.name}`:o;return s.some(i=>{if(!(t.getDataType(i.dataType||"")==="date"))return!1;const u=n.getSelectedDateFilterColumn(i,r),x=u.split("."),m=x[x.length-1]||u,f=x.length>1?x.slice(0,-1).join("."):void 0,g=i.qualifiedTableName||f,p=g?`${g}.${m}`:void 0;return o?p?p===c||p.endsWith(`.${o}`):m===a.name:p?p===c:m===a.name})}function bi({dashboard:s,dateGroupByField:a,dashboardInputValues:r,dashboardInputValuesAreAuthoritative:o,sheetId:d,card:c,timezone:i}){var m;if(!s||!a)return!1;const l=(m=s.inputs)==null?void 0:m.filter(f=>f.kind==="filter"&&!f.compatibility);if(!(l!=null&&l.length))return!1;const u={...s,inputs:l,filters:[],controls:[]};return n.resolveDashboardInputContext({dashboard:u,sheetId:d,card:c,sheetKind:"dashboard",runtimeValues:{dashboardInputValues:r,dashboardInputValuesAreAuthoritative:o},mode:"editor",timezone:i}).resolvedInputs.some(f=>f.kind!=="filter"||!f.filter||!f.filterValue?!1:Ea([f.filter],a,[f.filterValue]))}function ji({aliasTemplate:s,onAliasTemplateChange:a}){var u;const[r,o]=y.useState(s),[d,c]=y.useState(!1),i=(u=t.useEditorStore(x=>{var m;return(m=x.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],l=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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:l,value:d?r:s,onChange:x=>{o(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&d&&r!==s?(a(r),c(!1)):x.key==="Escape"&&(o(s),c(!1))},"aria-label":"Edit alias template"}),d&&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:()=>{o(s),c(!1)},children:e.jsx(ae.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function vi({valueAliases:s,onValueAliasesChange:a}){const[r,o]=y.useState(null),[d,c]=y.useState(""),[i,l]=y.useState(""),u=()=>{a({...s,"":""})},x=f=>{const g={...s};delete g[f],a(g)},m=f=>{const g={...s};delete g[f],g[d]=i,a(g),o(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(([f,g],p)=>e.jsx("div",{className:"flex items-center gap-2",children:r===f?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:h=>c(h.target.value),className:"h-8 w-24 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.key==="Enter"?m(f):h.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:i,onChange:h=>l(h.target.value),className:"h-8 w-24 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.key==="Enter"?m(f):h.key==="Escape"&&o(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:()=>m(f),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:()=>o(null),children:e.jsx(ae.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(f),c(f),l(g)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(f),c(f),l(g)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(f),"aria-label":"Remove value alias",children:e.jsx(ae.X,{className:"h-3 w-3"})})]})},f+p)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function yi({idx:s}){var l;const a=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=t.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.datasetOptions}),o=t.useEditorStore(u=>u.actions.setCardPreferences),d=(l=a==null?void 0:a.chartOptions)==null?void 0:l.indexAxis,c=r==null?void 0:r.find(u=>u.idx===s);function i(u,x){(u==="end"||u==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!c)o({...a,datasetOptions:[...r||[],{idx:x,datalabels:m}]});else{const f={...c};f.datalabels=m;const g=r==null?void 0:r.map(p=>p.idx===x?f:p);o({...a,datasetOptions:g})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(yr,{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:()=>i("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ae.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(dr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(mr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ur,{className:t.cn("h-4 w-4",{"rotate-90":d==="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 Ni(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Ci({col:s,idx:a,className:r,iconClassName:o,children:d}){const c=t.useEditorStore(m=>{var f;return(f=m.card)==null?void 0:f.preferences}),i=t.useEditorStore(m=>{var f,g;return(g=(f=m.card)==null?void 0:f.preferences)==null?void 0:g.datasetOptions}),l=i==null?void 0:i.find(m=>m.idx===a),{setCardPreferences:u}=t.useEditorStore(m=>m.actions);function x(m){if(!l)u({...c,datasetOptions:[...i||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const f={...l};f.type=m==="area"?"line":m,f.fill=m==="area"?"origin":"";const g=i==null?void 0:i.map(p=>p.idx===a?f:p);u({...c,datasetOptions:g})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[d||e.jsx(Vs,{className:"max-w-[100px]",title:s,children:Ni(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",o)}),e.jsx(n.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(yi,{idx:a})]})]})}function Si(){const s=t.useEditorStore(l=>l.card.type),a=t.useEditorStore(l=>l.isDevMode),r=t.useEditorStore(l=>l.card.preferences),{setCardPreferences:o}=t.useEditorStore(l=>l.actions);function d(l){var m;const u={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(m=r==null?void 0:r.chartOptions)==null?void 0:m.plugins,...u}}};o(x)}function c(){var l,u,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=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:d,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 i(){var l,u,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:d,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():i()})}function wi({column:s}){const a=t.useEditorStore(u=>u.card.type),r=t.useEditorStore(u=>{var x,m;return(m=(x=u.card)==null?void 0:x.config)==null?void 0:m.metricColumns}),o=(r==null?void 0:r.map(u=>u.label))||[],d=o==null?void 0:o.find(u=>u===s.label||u===s.name),c=d?o.indexOf(d):-1;function i(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx(Ci,{idx:c,col:d,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function l(){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(Si,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&l()]})}function Ti({field:s,searchQuery:a="",limit:r=500}){const{authToken:o,tokenProps:d}=n.useSemaphorContext(),c=t.useEditorStore(x=>x.card),i=c==null?void 0:c.dataSource,l=["attribute-values",s.entityName,s.name,a,r],u=n.useQuery({queryKey:l,queryFn:async()=>{if(!(i!=null&&i.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},m={connection_id:i.connectionId,cardConfig:x,cardDataSource:i,cache_config:t.getCacheConfig({card:c})};console.log("requestBody",m);const f=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",m);if(f!=null&&f.error)return console.error("Error fetching attribute values:",f.error),[];const g=s.name;return((f==null?void 0:f.records)||[]).map(h=>{const N=h[g]||h[s.alias||g]||h[s.label];return{id:N||"",value:N||"",label:String(N||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:u.data||[],isLoading:u.isLoading,isFetching:u.isFetching,isError:u.isError,error:u.error,refetch:u.refetch}}function Ia({open:s,onOpenChange:a,availableFields:r,existingFilters:o,editingCondition:d,onSave:c}){var P,C;const i=!!d,[l,u]=y.useState(i?"values":"fields"),[x,m]=y.useState(""),[f,g]=y.useState({id:(d==null?void 0:d.id)||t.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),p=r.filter(S=>{var I;return i?!1:!((I=o==null?void 0:o.conditions)==null?void 0:I.some(E=>E.field.id===S.id))&&S.label.toLowerCase().includes(x.toLowerCase())}),h=S=>{g({...f,field:S}),u("values")},N=()=>{if(f.field&&f.selectedValues.length>0){const S={id:f.id,field:f.field,operator:"in",value:f.selectedValues};let A;if(i){const I=((o==null?void 0:o.conditions)||[]).map(E=>E.id===d.id?S:E);A={...o,conditions:I}}else{const I=(o==null?void 0:o.conditions)||[];A={id:(o==null?void 0:o.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...I,S],groups:[]}}c(A),a(!1)}},b=()=>{if(!i||!d)return;const S=((o==null?void 0:o.conditions)||[]).filter(A=>A.id!==d.id);if(S.length>0){const A={...o,conditions:S};c(A)}else c(void 0);a(!1)},v=S=>{g({...f,selectedValues:S})},k=()=>{i&&d?(g({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),u("values")):(g({id:t.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return y.useEffect(()=>{s&&k()},[s,i,d]),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:i?`Edit Filter: ${(P=f.field)==null?void 0:P.label}`:l==="fields"?"Select Field to Filter":`Select Values for ${(C=f.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&l==="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:o.conditions.map(S=>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:[S.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(S.value)?`${S.value.length} values`:String(S.value)})]},S.id))})]}),l==="fields"&&!i?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(Ue.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:x,onChange:S=>m(S.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:()=>m(""),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(ae.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:p.map(S=>e.jsxs("button",{type:"button",onClick:()=>h(S),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(S.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:S.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[S.entityName,".",S.name]})]})]},S.id))}),p.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),p.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(Ei,{field:f.field,selectedValues:f.selectedValues,onValuesChange:v,onBack:i?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(t.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:k,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:N,disabled:!f.field||f.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ei({field:s,selectedValues:a,onValuesChange:r,onBack:o}){const[d,c]=y.useState(""),{values:i,isLoading:l,isFetching:u}=Ti({field:s,searchQuery:d,limit:500}),x=d?i.filter(g=>String(g.value).toLowerCase().includes(d.toLowerCase())):i,m=g=>{const p=a.includes(g);r(p?a.filter(h=>h!==g):[...a,g])},f=()=>{a.length===x.length&&x.length>0?r([]):r(x.map(g=>g.value))};return e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:o,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(Ue.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:d,onChange:g=>c(g.target.value),className:"pl-10"})]}),l||u?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:f}),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(g=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(g.value),children:[e.jsx(n.Checkbox,{checked:a.includes(g.value),onCheckedChange:()=>m(g.value)}),e.jsx(Vs,{className:"text-sm",children:g.label})]},g.id))})]})]})}function Ii({value:s,onChange:a,showTitle:r=!0,title:o="NUMBER FORMAT"}){const d=t.toTFormatOptions(t.fromSemanticFormat(s))||{},c=i=>{a(t.fromTFormatOptions(i))};return e.jsx(ls,{formatOptions:d,onFormatOptionsChange:c,showTitle:r,title:o})}const ki=[];function Di({field:s,zone:a,index:r,sortDirection:o,onSortDirectionChange:d,hasPivotColumns:c=!1,cardType:i}){var Qs,Ws,Ys,Js,Xs,Zs,en,tn,sn,nn,an,rn,on,ln,cn,dn,un,mn,xn,hn,pn,fn,gn,bn,jn,vn,yn,Nn,Cn,Sn,wn,Tn,En,In,kn,Dn,An;const{attributes:l,listeners:u,setNodeRef:x,transform:m,transition:f,isDragging:g}=n.useSortable({id:s.id}),p=t.useEditorStore(U=>U.card),h=t.useEditorStore(U=>U.frame),N=t.useDashboardStore(U=>U.isVisualEditing),b=t.useDashboardStore(U=>U.selectedSheetId),v=t.useDashboardStore(U=>U.actions.updateSheetCalculatedFields),k=t.useDashboardStore(U=>U.actions.updateDashboardCalculatedFields),C=t.useDashboardStore(U=>{var he;return U.visualEditPendingDashboardCalculatedFields??((he=U.dashboard)==null?void 0:he.calculatedFields)})??ki,{scopedFields:S,valuePickFilterableFields:A,isLoading:I}=n.useFilterableFields(),{userContext:E}=n.useCurrentUserInfo(),{tokenProps:w}=n.useSemaphorContext(),D=(E==null?void 0:E.type)==="organization",F=((Ws=(Qs=w==null?void 0:w.params)==null?void 0:Qs.calendarContext)==null?void 0:Ws.tz)||((Ys=w==null?void 0:w.params)==null?void 0:Ys.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{updateLabel:V,handleAggregationChange:R,handleDateFormatChange:j,handleGranularityChange:T,handleAliasTemplateChange:L,handleValueAliasesChange:O,handleMetricFormatChange:B,removeField:z,handleMetricComparisonChange:_,handleMetricComparisonSpecChange:q,handleMetricComparisonPolarityChange:G,handleMetricWindowTransformChange:H,handleMetricWindowOrderByChange:$,handleMetricWindowDirectionChange:W,handleMetricWindowPartitionToggle:Q,handleMetricMovingAverageWindowSizeChange:se,handleMetricMovingAverageMinPeriodsChange:ue,handleMetricPreviousPeriodDeltaModeChange:pe,handleMetricPercentOfTotalScopeChange:ge,handleMetricPercentOfTotalOutputChange:ve,handleKpiShowTrendlineChange:Pe,handleKpiTrendlineWindowChange:Ve,handleKpiTrendlineGranularityChange:ee,handleMetricTargetValueChange:xe}=n.useFieldManagement(p),[Ee,qe]=y.useState(!1),[$e,ce]=y.useState(()=>{var U;return!!((U=s.parameters)!=null&&U.windowTransform)}),[Re,we]=y.useState(!1),[ie,K]=y.useState(!1),[le,me]=y.useState(null),te=y.useMemo(()=>{const U=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,he=U(s.id),J=S.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 Ne=U(oe.id);return!!(he&&Ne&&he===Ne)});return{dataType:(J==null?void 0:J.dataType)||s.dataType,resolvedFromScopedField:!!J}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,S]),de=n.getGranularityOptionsForFieldType(te.dataType),[Le,Me]=y.useState(s.dateFormat||"YYYY-MM-DD"),[Qe,re]=y.useState(s.customFormat||""),[je,Ce]=y.useState(!!s.customFormat),ne=y.useRef(null),[Ie,ke]=y.useState(s.aliasTemplate||""),[Be,We]=y.useState(s.valueAliases||{}),[Se,De]=y.useState((Js=s.parameters)==null?void 0:Js.filters),et=U=>{U==="custom"?Ce(!0):(Ce(!1),Me(U),(a==="groupBy"||Ft)&&j(r,U,"",a))},Fe=U=>{re(U),(a==="groupBy"||Ft)&&j(r,"custom",U,a)},Gt=U=>{var oe;const J=(oe=n.getDateFormatOptionsForGranularity(U)[0])==null?void 0:oe.value;J&&!je&&(Me(J),a==="groupBy"&&j(r,J,"",a)),a==="groupBy"&&T(r,U)},Ct=U=>{ke(U),a==="metrics"&&L(r,U)},ds=U=>{We(U),a==="metrics"&&O(r,U)},ut=U=>{V(a,r,U)},St=n.getExpressionFieldKind(s),Ht=n.getFieldExpressionAnnotation(s),bt=n.isManagedCalculatedExpressionField(s),Lt=s.role==="metric"&&bt,jt=bt&&(St==="user_calculated"||St==="inline_expression"&&s.fieldScope!=="domain"),tt=jt?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(h==null?void 0:h.calculatedFields)||[],dashboardFields:C}):void 0,Qt=jt&&(tt==null?void 0:tt.scope)==="sheet",Mt=jt&&(tt==null?void 0:tt.scope)==="dashboard",mt=St==="domain_calculated"||s.fieldScope==="domain",Wt=mt?n.resolveDomainCalculatedFieldForEdit(s,S):void 0,it=mt?"domain":Qt?"sheet":Mt?"dashboard":"card",xt=mt?Wt||s:(Qt||Mt)&&(tt!=null&&tt.matchedField)?tt.matchedField:s,ht=U=>{var he;if(De(U),a==="metrics"){const J={...s,parameters:{...s.parameters,filters:U}},oe=[...((he=p.config)==null?void 0:he.metricColumns)||[]];oe[r]=J,t.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:oe})}we(!1)},zs=()=>{z(a,r)},Yt={transform:n.CSS.Transform.toString(m),transition:f},Jt=t.getDataType(te.dataType||s.dataType),wt=Jt==="date",Rt=i==="kpi",Ft=a==="detailColumns",Xt=(Xs=p.config)==null?void 0:Xs.metricColumns,pt=(Zs=p.config)==null?void 0:Zs.groupByColumns,Ot=t.useDashboardStore(U=>U.dashboard),Zt=t.useDashboardStore(U=>{var he;return(he=U.dashboard)==null?void 0:he.filters}),vt=t.useDashboardStore(U=>U.filterValues),Pt=t.useDashboardStore(U=>U.dashboardInputValues),Vt=t.useDashboardStore(U=>U.dashboardInputValuesAreAuthoritative),Y=t.useDashboardStore(U=>U.semanticExecutionPayload),X=s.granularity||"day",Z=de.includes(X)?X:"day",be=a==="groupBy"&&!de.includes(X),fe=n.getDateFormatOptionsForGranularity(Z),ye=je?"custom":fe.some(U=>U.value===Le)?Le:((en=fe[0])==null?void 0:en.value)??"YYYY-MM-DD";y.useEffect(()=>{var J;if(I||!be){ne.current=null;return}const U=`${s.id}:${X}:${te.dataType||s.dataType||""}:${r}`;if(ne.current===U)return;ne.current=U;const he="day";if(T(r,he),!je){const oe=(J=n.getDateFormatOptionsForGranularity(he)[0])==null?void 0:J.value;oe&&(Me(oe),j(r,oe,"",a))}},[s.dataType,s.id,j,T,be,r,je,I,X,te.dataType,a]);const Ke=!!i&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(i),Ye=!!i&&t.COMPARISON_TARGET_SUPPORTED_CHART_TYPES.includes(i),nt=y.useMemo(()=>pt==null?void 0:pt.find(U=>t.getDataType(U.dataType||"")==="date"),[pt]),st=y.useMemo(()=>t.resolveCardPrimaryDateField({card:p,cardConfig:p.config||{},semanticExecutionPayload:Y}),[p,Y]),_e=y.useMemo(()=>nt||(st?{...st,id:`semantic-primary:${st.entityId}:${st.name}`,label:st.name,role:"groupby",granularity:st.defaultGranularity||"day"}:void 0),[nt,st]),He=y.useMemo(()=>{var oe;if(!_e)return!1;const U=(oe=p.config)==null?void 0:oe.filters;if(!U)return!1;const he=Ne=>{const Ge=Ne.field;return Ge?_e.id&&Ge.id===_e.id||_e.qualifiedFieldName&&Ge.qualifiedFieldName===_e.qualifiedFieldName?!0:Ge.name===_e.name:!1},J=Ne=>Ne.conditions.some(ze=>t.getDataType(ze.field.dataType||"")==="date"&&he(ze))?!0:Ne.groups.some(ze=>J(ze));return J(U)},[(tn=p.config)==null?void 0:tn.filters,_e]),Tt=y.useMemo(()=>Ea(Zt||[],_e,vt)||bi({dashboard:Ot,dateGroupByField:_e,dashboardInputValues:Pt,dashboardInputValuesAreAuthoritative:Vt,sheetId:b,card:p,timezone:F}),[p,Ot,Zt,vt,Pt,Vt,_e,b,F]),es=He||Tt,Ae=s,Je=((sn=Ae.comparison)==null?void 0:sn.mode)==="explicit"?Ae.comparison.spec:void 0,us=((an=(nn=Ae.parameters)==null?void 0:nn.windowTransform)==null?void 0:an.function)||"none",at=n.isMetricTransformEnabled(Ae),rt=at?us:null,ms=n.supportsMetricTransformForMetric({cardType:i||"table",cardConfig:p.config||{},metric:Ae,transformMode:rt||"running_total"}),Bt=((rn=Ae.comparison)==null?void 0:rn.mode)==="explicit",qs=n.getRunningTotalOrderByCandidates(pt||[]),Et=((cn=(ln=(on=Ae.parameters)==null?void 0:on.windowTransform)==null?void 0:ln.orderBy)==null?void 0:cn.fieldId)||"",Da=((mn=(un=(dn=Ae.parameters)==null?void 0:dn.windowTransform)==null?void 0:un.orderBy)==null?void 0:mn.direction)||"asc",$s=qs.find(U=>U.id===Et),xs=rt==="running_total"||rt==="moving_average"||rt==="previous_period_delta",Aa=at&&xs&&!!$s&&t.getDataType($s.dataType||"")!=="date",La=n.getDefaultRunningTotalPartitionByFieldIds({cardType:i||"table",cardConfig:p.config||{},orderByFieldId:Et||void 0}),Ma=new Set(((hn=(xn=Ae.parameters)==null?void 0:xn.windowTransform)==null?void 0:hn.partitionByFieldIds)||La),Ra=i==="pivotTable"||n.isSubtotalEnabledAggregateTable(i||"table",p.config||{}),Ks=[...(pt||[]).filter(U=>U.id&&(!xs||U.id!==Et)),...Ra?(((pn=p.config)==null?void 0:pn.pivotByColumns)||[]).filter(U=>U.id):[]],Us=((bn=(gn=(fn=Ae.parameters)==null?void 0:fn.windowTransform)==null?void 0:gn.movingAverage)==null?void 0:bn.windowSize)||7,Fa=((yn=(vn=(jn=Ae.parameters)==null?void 0:jn.windowTransform)==null?void 0:vn.movingAverage)==null?void 0:yn.minPeriods)||1,Oa=((Sn=(Cn=(Nn=Ae.parameters)==null?void 0:Nn.windowTransform)==null?void 0:Cn.previousPeriodDelta)==null?void 0:Sn.mode)||"absolute",Gs=((En=(Tn=(wn=Ae.parameters)==null?void 0:wn.windowTransform)==null?void 0:Tn.percentOfTotal)==null?void 0:En.scope)||"grand_total",Pa=((Dn=(kn=(In=Ae.parameters)==null?void 0:In.windowTransform)==null?void 0:kn.percentOfTotal)==null?void 0:Dn.output)||"percent",Va=y.useMemo(()=>(Xt||[]).some(()=>!1),[Xt]);y.useEffect(()=>{at&&ce(!0)},[at]);const Ba=a!=="pivotBy"&&a!=="sortBy",_a=wt&&a==="groupBy"&&(!Rt||Va),za=!Rt&&wt&&(a==="groupBy"||Ft),qa=i==="kpi"&&wt&&a==="groupBy",$a=a==="metrics",ts=Ke&&!p.sql&&!p.python&&a==="metrics",Ka=()=>{const U=s,he=a==="metrics"&&Lt;return e.jsxs("div",{className:"space-y-1",children:[!he&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:J=>{J.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}`}),he&&U.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(U.calculatedFormula),onPointerDown:J=>{J.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(U.calculatedFormula)]})]})},Ua=()=>Ba?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(lt,{value:s.label??"",onSave:ut,placeholder:"Display label...",type:"text"})]}):null,Ga=()=>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:o||"asc",onValueChange:U=>d(U),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"})]})]})]}),Hs=()=>_a?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:Z,onValueChange:Gt,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:de.map(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U,children:t.toTitleCase(U)},U))})]})]}):null,Ha=()=>za?e.jsxs(e.Fragment,{children:[Hs(),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:ye,onValueChange:et,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:fe.map(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),je&&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:Qe,onChange:U=>{U.stopPropagation(),Fe(U.target.value)},onClick:U=>U.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,Qa=()=>{var he,J,oe,Ne;const U=qa;return U?e.jsx(e.Fragment,{children:U&&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:((he=p.config)==null?void 0:he.showTrendline)||!1,onCheckedChange:Pe})]})}),((J=p.config)==null?void 0:J.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=p.config)==null?void 0:oe.trendlineWindow)||30,onChange:Ge=>{const ze=parseInt(Ge.target.value)||30;Ve(ze)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Ne=p.config)==null?void 0:Ne.trendlineGranularity)||"day",onValueChange:ee,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},Wa=()=>{var he;if(!$a)return null;const U=Lt;return e.jsxs(e.Fragment,{children:[U&&D&&!mt&&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:()=>K(!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:J=>{R(r,J)},disabled:U,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(Ii,{value:Ae.format,onChange:J=>B(r,J),showTitle:!1})]}),e.jsx(n.Collapsible,{open:$e,onOpenChange:ce,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(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:[!$e&&e.jsx("span",{className:"mr-2",children:at?t.toTitleCase(us.replace(/_/g," ")):"None"}),e.jsx(ae.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",$e?"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:at?us:"none",onValueChange:J=>H(r,J),disabled:!ms.supported&&!at,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:Bt,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:Bt,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:Bt,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:Bt,children:"Percent of Total"})]})]}),!ms.supported&&!at&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ms.reason}),Bt&&!at&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),at&&e.jsxs(e.Fragment,{children:[xs&&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:Et,onValueChange:J=>$(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:qs.filter(J=>!!J.id).map(J=>e.jsx(t.SelectItem,{value:J.id,className:"text-xs",children:J.label||J.name},J.id))})]}),!Et&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Aa&&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:Da,onValueChange:J=>W(r,J),disabled:!Et,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"})]})]})]})]}),rt==="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:Us,onChange:J=>se(r,Number(J.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:Us,className:"h-8 text-xs",value:Fa,onChange:J=>ue(r,Number(J.target.value))})]}),rt==="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:Oa,onValueChange:J=>pe(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),rt==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:Gs,onValueChange:J=>ge(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Pa,onValueChange:J=>ve(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(rt==="running_total"||rt==="moving_average"||rt==="previous_period_delta"||rt==="percent_of_total"&&Gs==="partition_total")&&Ks.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:Ks.map(J=>{const oe=!!J.id&&Ma.has(J.id);return e.jsxs("button",{type:"button",onClick:()=>J.id&&Q(r,J.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",oe?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:J.label||J.name}),oe?e.jsx(t.Check,{className:"h-3 w-3"}):null]},J.id)})})]})]})]})]})}),ts&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:Ae.comparison?Ae.comparison.mode==="off"?"off":Ae.comparison.spec.kind:"inherit",disabled:at,onValueChange:J=>_(r,J),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"inherit",children:"Inherit dashboard comparison (default)"}),e.jsx(t.SelectItem,{value:"off",children:"Off"}),(()=>{const J=!_e||!es,oe=_e?es?void 0:"Add a date filter to enable":"Configure a semantic primary date or add a date axis",Ne=(Ge,ze)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ge,disabled:J,title:oe,children:ze})}),J&&oe&&e.jsx(t.TooltipContent,{side:"right",children:oe})]})});return e.jsxs(e.Fragment,{children:[Ne("previous_period","Previous Period"),Ne("previous_year","Previous Year")]})})(),Ye&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]}),!Ae.comparison&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Dashboard comparison is not available yet. This metric will follow it when a viewer sets it."})]}),ts&&Je&&(Je.kind==="previous_period"||Je.kind==="previous_year")&&e.jsxs("div",{className:"space-y-2 rounded border border-border/60 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:Je.kind==="previous_year"?"Years back":"Periods back"}),e.jsx(t.Input,{type:"number",min:1,step:1,value:Je.kind==="previous_year"?Je.offsetYears||1:Je.offsetPeriods||1,onChange:J=>{const oe=Number(J.target.value);!Number.isSafeInteger(oe)||oe<=0||(Je.kind==="previous_year"?q(r,{...Je,offsetYears:oe===1?void 0:oe}):q(r,{...Je,offsetPeriods:oe===1?void 0:oe}))},className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Alignment"}),e.jsxs(t.Select,{value:Je.alignment||"calendar",onValueChange:J=>q(r,{...Je,alignment:J==="calendar"?void 0:J}),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,{value:"calendar",children:"Calendar"}),e.jsx(t.SelectItem,{value:"weekday",children:"Match weekdays"})]})]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"To date"}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Match the elapsed portion of an incomplete current window."})]}),e.jsx(t.Switch,{size:"xs",checked:Je.toDate===!0,onCheckedChange:J=>q(r,{...Je,toDate:J?!0:void 0})})]}),e.jsxs("p",{className:"text-[11px] leading-4 text-muted-foreground",children:["Anchored to"," ",e.jsx("span",{className:"text-foreground",children:(_e==null?void 0:_e.label)||(_e==null?void 0:_e.name)}),". The resolved comparison dates appear after the card runs."]})]}),ts&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Favorable direction"}),e.jsxs(t.Select,{value:t.getMetricComparisonPolarity(Ae),disabled:!!Ae.semanticComparisonPolarity,onValueChange:J=>G(r,J),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,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),Ae.semanticComparisonPolarity&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Governed by this metric's semantic definition."})]}),ts&&((he=Ae.comparison)==null?void 0:he.mode)==="explicit"&&Ae.comparison.spec.kind==="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:Ae.comparison.spec.targetValue!==void 0&&Ae.comparison.spec.targetValue!==null?String(Ae.comparison.spec.targetValue):"",onChange:J=>{const oe=J.target.value;if(oe===""){xe(r,void 0);return}const Ne=Number(oe);xe(r,Number.isFinite(Ne)?Ne: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"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(J=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{me(J),we(!0)},children:[e.jsxs("span",{className:"font-medium",children:[J.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(J.value)?J.value.length===1?String(J.value[0]):J.value.length<=2?J.value.join(", "):`${J.value.slice(0,2).join(", ")} +${J.value.length-2}`:String(J.value)})}),Array.isArray(J.value)&&J.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",J.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:J.value.map((oe,Ne)=>e.jsx("div",{children:String(oe)},Ne))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var Ge;oe.stopPropagation();const Ne=Se.conditions.filter(ze=>ze.id!==J.id);if(Ne.length>0){const ze={...Se,conditions:Ne};ht(ze)}else if(De(void 0),a==="metrics"){const ze={...s,parameters:{...s.parameters,filters:void 0}},Xe=[...((Ge=p.config)==null?void 0:Ge.metricColumns)||[]];Xe[r]=ze,t.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Xe})}},children:e.jsx(ae.X,{className:"h-3 w-3"})})]},J.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{me(null),we(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(wi,{column:s}),c&&e.jsxs(e.Fragment,{children:[e.jsx(ji,{aliasTemplate:Ie,onAliasTemplateChange:Ct}),e.jsx(vi,{valueAliases:Be,onValueAliasesChange:ds})]})]})};Se!=null&&Se.conditions&&Se.conditions.length>0;const Ya=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{open:Ee,onOpenChange:qe,children:[e.jsxs("div",{ref:x,style:Yt,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",Ee?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",g&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...l,...u,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:U=>{U.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:Jt,calculated:!!Ht}),e.jsx(Vs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((An=Se==null?void 0:Se.conditions)==null?void 0:An.length)&&!Ee&&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:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":o==="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:U=>{U.stopPropagation(),d(o==="asc"?"desc":"asc")},children:o==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),Ya&&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:U=>U.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:U=>{U.stopPropagation(),zs()},children:e.jsx(ae.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:[Ka(),Ga(),Ua(),i==="kpi"&&Hs(),Ha(),Qa(),Wa()]})})]}),Re&&e.jsx(Ia,{open:Re,onOpenChange:U=>{we(U),U||me(null)},availableFields:A,existingFilters:Se,editingCondition:le,onSave:U=>{var he;if(U)ht(U);else if(De(void 0),a==="metrics"){const J={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((he=p.config)==null?void 0:he.metricColumns)||[]];oe[r]=J,t.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:oe})}me(null)}}),ie&&a==="metrics"&&Lt&&e.jsx(n.CalculatedFieldEditor,{open:ie,onOpenChange:K,availableFields:S,existingField:xt,existingFieldScope:it,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:U=>{var It,ct;if(U.role!=="metric")return;const{card:he,frame:J,actions:oe}=t.useEditorStore.getState(),Ne=((It=he.config)==null?void 0:It.metricColumns)||[],Ge=((ct=he.config)==null?void 0:ct.sortByColumns)||[],ze=it==="dashboard"?C:J.calculatedFields||[],{nextActiveFields:Xe,nextSortByFields:ot,nextStoredFields:dt,nextSharedFields:ft}=n.saveCalculatedFieldToCardScope({activeFields:Ne,sortByFields:Ge,storedFields:he.calculatedFields||[],sharedFields:ze,updatedField:U,editingField:xt,previousScope:it});(Xe||ot)&&oe.updateCardConfig(p.id,{...Xe?{metricColumns:Xe}:{},...ot?{sortByColumns:ot}:{}}),oe.updateCard(p.id,{calculatedFields:dt}),it==="dashboard"&&ft!==ze?k(ft):ft!==ze&&n.commitSharedCalculatedFields({nextSharedFields:ft,currentSharedFields:ze,isVisualEditing:N,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:v})},onSaveToSheet:U=>{var _t,zt;if(U.role!=="metric")return;const{card:he,frame:J,actions:oe}=t.useEditorStore.getState(),Ne=s,Ge=((_t=he.config)==null?void 0:_t.metricColumns)||[],ze=((zt=he.config)==null?void 0:zt.sortByColumns)||[],Xe=J.calculatedFields||[],{nextActiveFields:ot,nextSortByFields:dt,nextStoredFields:ft,nextSheetFields:It,nextDashboardFields:ct}=n.saveCalculatedFieldToSheetScope({activeFields:Ge,sortByFields:ze,storedFields:he.calculatedFields||[],sheetFields:Xe,dashboardFields:C,updatedField:{...U,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:xt,previousScope:it});n.commitSharedCalculatedFields({nextSharedFields:It,currentSharedFields:Xe,isVisualEditing:N,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:v}),ct&&ct!==C&&k(ct),(ot||dt)&&oe.updateCardConfig(p.id,{...ot?{metricColumns:ot}:{},...dt?{sortByColumns:dt}:{}}),oe.updateCard(p.id,{calculatedFields:ft})},onSaveToDashboard:U=>{var _t,zt;if(U.role!=="metric")return;const{card:he,frame:J,actions:oe}=t.useEditorStore.getState(),Ne=s,Ge=((_t=he.config)==null?void 0:_t.metricColumns)||[],ze=((zt=he.config)==null?void 0:zt.sortByColumns)||[],Xe=J.calculatedFields||[],{nextActiveFields:ot,nextSortByFields:dt,nextStoredFields:ft,nextSharedFields:It,nextSheetFields:ct}=n.saveCalculatedFieldToSharedScope({activeFields:Ge,sortByFields:ze,storedFields:he.calculatedFields||[],sharedFields:C,sheetFields:Xe,updatedField:{...U,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:xt,previousScope:it});k(It),ct&&ct!==Xe&&n.commitSharedCalculatedFields({nextSharedFields:ct,currentSharedFields:Xe,isVisualEditing:N,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:v}),(ot||dt)&&oe.updateCardConfig(p.id,{...ot?{metricColumns:ot}:{},...dt?{sortByColumns:dt}:{}}),oe.updateCard(p.id,{calculatedFields:ft})},cardId:p.id})]})}function Ai({concept:s}){const{title:a,description:r}=Li[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(Mi,{highlight:s})]})]})}const Li={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 Mi({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",o=s==="metrics",d="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&&d),children:c},c))]})}),e.jsx("tbody",{children:Xn.map((c,i)=>e.jsxs("tr",{className:t.cn(i!==Xn.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&&d),children:c.label}),c.values.map((l,u)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&d),children:l},u))]},c.label))})]})})}const Xn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],Ri={groupBy:n.Rows3,pivotBy:As,metrics:gr,detailColumns:t.Table2,sortBy:ea};function $t({zone:s,fields:a,label:r,placeholder:o,shouldShow:d,hasPivotColumns:c=!1,activeField:i=null}){const{isOver:l,setNodeRef:u}=n.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),m=t.useEditorStore(v=>v.card),f=t.useEditorStore(v=>v.card.type),g=a.length>0,p=y.useMemo(()=>!i||!l?!0:n.validateFieldForChartType(i,s,f).isValid,[i,l,s,f]),h=(v,k)=>{var C;!((C=m.config)!=null&&C.sortByColumns)||m.config.sortByColumns.findIndex(S=>S.id===v)===-1||x(m.id,v,{direction:k})};if(s==="sortBy"&&d===!1)return null;const N=s!=="sortBy"&&f!=="kpi",b=Ri[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:u,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":l&&p,"border border-destructive/40 bg-destructive/5":l&&!p,"border border-dashed border-border/50 bg-background":!l&&!g}),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:o}),N&&e.jsx(Ai,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(v=>v.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((v,k)=>{const C=v.direction;return e.jsx(Di,{field:v,zone:s,index:k,sortDirection:C,onSortDirectionChange:S=>h(v.id,S),hasPivotColumns:c,cardType:f},v.id)})})})})]})}const Fi=[];function Oi({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:o,detailFields:d,activeField:c}){var H,$,W;const[i,l]=y.useState(!1);t.useEditorStore(Q=>{var se;return!!((se=Q.card.customCardPreferences)!=null&&se.url)});const u=t.useEditorStore(Q=>Q.card),x=t.useEditorStore(Q=>Q.frame),m=n.findCustomVisualConfigCard(x,u),{manifest:f}=n.useCustomVisual(((H=m==null?void 0:m.customCardPreferences)==null?void 0:H.url)||""),g=($=f==null?void 0:f.visuals)==null?void 0:$.find(Q=>{var se;return Q.name===((se=m==null?void 0:m.customCardPreferences)==null?void 0:se.componentName)}),p=n.resolveMultiInputType(m,g)==="multiple";p&&((W=m==null?void 0:m.customCardPreferences)!=null&&W.url);const h=n.getConfigSlotExpectedType(g==null?void 0:g.slots),N=t.useEditorStore(Q=>Q.actions.updateCardConfig),b=t.useEditorStore(Q=>Q.actions.updateCard),v=t.useEditorStore(Q=>Q.actions.updateFrame),k=t.useDashboardStore(Q=>Q.isVisualEditing),P=t.useDashboardStore(Q=>Q.selectedSheetId),C=t.useDashboardStore(Q=>Q.actions.updateSheetCalculatedFields),S=t.useDashboardStore(Q=>Q.actions.updateDashboardCalculatedFields),I=t.useDashboardStore(Q=>{var se;return Q.visualEditPendingDashboardCalculatedFields??((se=Q.dashboard)==null?void 0:se.calculatedFields)})??Fi,{scopedFields:E}=n.useScopedFields(),{userContext:w}=n.useCurrentUserInfo(),D=p&&(m==null?void 0:m.id)===u.id&&h?h:u==null?void 0:u.type,M=D==="detailTable",F=s.length>0||r.length>0||d.length>0,V=!M&&(D!=="kpi"||r.length<=2),R=!M,j=!M&&D!=="kpi",T=D!=="kpi"&&F,L=M,O="Drop sort fields here",B=(w==null?void 0:w.type)==="organization",z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(D),_=j&&!z,q=()=>D==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},G=()=>D==="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"}),F&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{N(u.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:[V&&e.jsx($t,{zone:"groupBy",fields:s,label:q().label,placeholder:q().placeholder,activeField:c}),_&&e.jsx($t,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:c}),R&&e.jsx($t,{zone:"metrics",fields:r,label:G().label,placeholder:G().placeholder,hasPivotColumns:a.length>0,activeField:c}),L&&e.jsx($t,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&B&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>l(!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"]}),T&&e.jsx($t,{zone:"sortBy",fields:o,label:"Sort By",placeholder:O,activeField:c})]}),e.jsx(n.CalculatedFieldEditor,{open:i,onOpenChange:l,availableFields:E,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Q=>{if(Q.role!=="metric")return;const{nextStoredFields:se}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:x.calculatedFields||[],updatedField:Q,previousScope:"card"});b(u.id,{calculatedFields:se})},onSaveToSheet:Q=>{if(Q.role!=="metric")return;const se=x.calculatedFields||[],{nextSheetFields:ue}=n.saveCalculatedFieldToSheetScope({activeFields:r,storedFields:u.calculatedFields||[],sheetFields:se,updatedField:Q,previousScope:"sheet"});n.commitSharedCalculatedFields({nextSharedFields:ue,currentSharedFields:se,isVisualEditing:k,selectedSheetId:P,updateFrame:v,updateSheetCalculatedFields:C})},onSaveToDashboard:Q=>{if(Q.role!=="metric")return;const{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:I,updatedField:Q,previousScope:"dashboard"});S(se)},cardId:u.id})]})}function Pi(){var k,P,C;const s=t.useEditorStore(S=>{var A;return(A=S.card)==null?void 0:A.type}),a=s==="kpi",[r,o]=y.useState(a),[d,c]=y.useState(!1),i=t.useEditorStore(S=>{var A;return!!((A=S.card.customCardPreferences)!=null&&A.url)}),l=t.useEditorStore(S=>S.card),u=t.useEditorStore(S=>S.frame),x=n.findCustomVisualConfigCard(u,l),{manifest:m}=n.useCustomVisual(((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.url)||""),f=(P=m==null?void 0:m.visuals)==null?void 0:P.find(S=>{var A;return S.name===((A=x==null?void 0:x.customCardPreferences)==null?void 0:A.componentName)}),p=n.resolveMultiInputType(x,f)==="multiple"&&!!((C=x==null?void 0:x.customCardPreferences)!=null&&C.url),h=!i||p,N=i||p,b=a?"KPI Settings":"Chart Settings",v=h&&!t.isTableChartType(s);return y.useEffect(()=>{a&&o(!0)},[a]),!v&&!N?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[v&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",a?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60 [&_h3]:sticky [&_h3]:top-0 [&_h3]:z-10 [&_h3]:bg-background",children:e.jsx(Ta,{mode:"config"})})}),v&&e.jsxs("button",{type:"button",onClick:()=>o(S=>!S),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:b})]}),e.jsx(ae.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),N&&d&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(ya,{})}),N&&e.jsxs("button",{type:"button",onClick:()=>c(S=>!S),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",v&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ta,{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(ae.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",d&&"rotate-180"),strokeWidth:1.75})]})]})}function Vi({onEditJoins:s}){const a=t.useEditorStore(u=>u.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,d=(o==null?void 0:o.joins)||[];if(d.length===0)return null;const c=u=>!u||u.length===0?"No conditions":u.map(x=>{var p,h,N,b;const m=`${(p=x.source)==null?void 0:p.entityName}.${(h=x.source)==null?void 0:h.name}`,f=`${(N=x.target)==null?void 0:N.entityName}.${(b=x.target)==null?void 0:b.name}`,g=x.operator||"=";return`${m} ${g} ${f}`}).join(" AND "),i=u=>!u.joinKeyGroups||u.joinKeyGroups.length===0?"No conditions defined":u.joinKeyGroups.length===1?c(u.joinKeyGroups[0].keys):u.joinKeyGroups.map((x,m)=>({id:m,operator:x.operator,condition:c(x.keys)})),l=e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"shrink-0 cursor-help rounded-control px-1 font-mono text-[10px] tabular-nums text-muted-foreground/70 transition-colors hover:bg-muted hover:text-foreground","aria-label":`${d.length} resolved ${d.length===1?"join":"joins"}`,children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md border border-border bg-popover p-2 text-popover-foreground shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsx("div",{className:"space-y-2",children:d.map((u,x)=>{const m=i(u),f=Array.isArray(m);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2 text-foreground",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:u.source.name}),e.jsx(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:u.target.name})]}),e.jsx("span",{className:"shrink-0 rounded-[3px] border border-border px-1 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:u.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:f?m.map(g=>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:g.condition}),g.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",g.operator,")"]})]},g.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},u.id||x)})})})]})});return e.jsxs("div",{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",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:"Resolved joins"}),l,s&&e.jsx("button",{type:"button",onClick:s,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 focus:outline-none focus-visible:border-ring","aria-label":"Edit resolved joins",children:e.jsx(n.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function Bi({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:o,groupByFields:d,pivotByFields:c,metricsFields:i,sortByFields:l,detailFields:u,activeField:x}){var I,E;const[m,f]=y.useState(!1),g=t.useEditorStore(w=>w.card),p=t.useEditorStore(w=>w.editorContext),h=t.useEditorStore(w=>w.actions.updateCardConfig),N=(p==null?void 0:p.type)==="documentSection",{autoJoinMetadata:b}=n.useEditorCardQuery(g),v=((I=g==null?void 0:g.config)==null?void 0:I.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),k=((E=g==null?void 0:g.dataSource)==null?void 0:E.selectedEntities)||[],P=w=>{h(g.id,{...g==null?void 0:g.config,joinPlan:w}),f(!1)},C=()=>{h(g.id,{...g==null?void 0:g.config,joinPlan:void 0}),f(!1)},S=()=>{f(!1)},A=()=>{f(!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:[!N&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(So,{selectedChart:s,onChartChange:a})}),o&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:o,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(Vi,{onEditJoins:A})}),e.jsx(Oi,{groupByFields:d,pivotByFields:c,metricsFields:i,sortByFields:l,detailFields:u,activeField:x})]}),e.jsx(Pi,{}),e.jsx(oa,{open:m,onOpenChange:f,joinPlan:v,availableDataSources:k,onSave:P,onCancel:S,onRemove:C,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:o&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:o,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(Ue.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function _i({initialFilters:s,availableFields:a}={}){const[r,o]=y.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:d,isLoading:c}=n.useFilterableFields(),i=a||d||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const S=A=>{if(A.id===C){const I=i[0]||l,E=t.getDataType(I.dataType)==="date";return{...A,conditions:[...A.conditions,{id:`condition-${Date.now()}`,field:I,operator:E?"between":"=",value:E?[]:""}]}}return{...A,groups:A.groups.map(S)}};o(S(r))},x=C=>{const S=A=>{if(A.id===C){const I=i[0]||l,E=t.getDataType(I.dataType)==="date";return{...A,groups:[...A.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:I,operator:E?"between":"=",value:E?[]:""}],groups:[]}]}}return{...A,groups:A.groups.map(S)}};o(S(r))},m=(C,S)=>{const A=I=>I.id===C?{...I,conditions:I.conditions.filter(E=>E.id!==S)}:{...I,groups:I.groups.map(A)};o(A(r))},f=(C,S)=>{const A=I=>I.id===C?{...I,groups:I.groups.filter(E=>E.id!==S)}:{...I,groups:I.groups.map(A)};o(A(r))},g=(C,S,A,I)=>{if(A==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const E=w=>w.id===C?{...w,conditions:w.conditions.map(D=>D.id===S?{...D,[A]:I}:D)}:{...w,groups:w.groups.map(E)};o(E(r))},p=(C,S,A)=>{const I=E=>E.id===C?{...E,conditions:E.conditions.map(w=>w.id===S?{...w,...A}:w)}:{...E,groups:E.groups.map(I)};o(I(r))},h=(C,S)=>{const A=I=>I.id===C?{...I,logicalOperator:S}:{...I,groups:I.groups.map(A)};o(A(r))},N=(C,S)=>{const A=I=>I.id===C?{...I,negate:S}:{...I,groups:I.groups.map(A)};o(A(r))},b=(C,S,A)=>{const I=E=>E.id===C?{...E,conditions:n.arrayMove(E.conditions,S,A)}:{...E,groups:E.groups.map(I)};o(I(r))},v=(C,S,A)=>{const I=E=>E.id===C?{...E,groups:n.arrayMove(E.groups,S,A)}:{...E,groups:E.groups.map(I)};o(I(r))},k=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const S=I=>{let E="";typeof I.field=="object"?E=I.field.entityName?`${I.field.entityName}.${I.field.name}`:I.field.name:E=String(I.field);const w=I.operator;let D=I.value;if(I.field.dataType==="string"&&!["in","not in"].includes(I.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(I.field.dataType==="date"||I.field.dataType==="datetime"||I.field.dataType==="timestamp")if(I.operator==="between"&&Array.isArray(D)&&D.length===2){const M=D[0]?`'${D[0]}'`:"NULL",F=D[1]?`'${D[1]}'`:"NULL";return`${E} BETWEEN ${M} AND ${F}`}else if((I.operator==="in"||I.operator==="not in")&&Array.isArray(D)){const M=D.map(F=>F?`'${F}'`:"NULL").join(", ");return`${E} ${w} (${M})`}else typeof D=="string"||D instanceof Date?D=`'${D}'`:Array.isArray(D)&&D.length>0&&(D=`'${D[0]}'`);else if(["in","not in"].includes(I.operator)){let M=[];Array.isArray(D)?M=D.map(F=>typeof F=="string"?`'${F}'`:String(F)):typeof D=="string"?M=D.split(",").map(F=>{const V=F.trim();return I.field.dataType==="string"?`'${V}'`:V}):typeof D=="number"&&(M=[String(D)]),D=`(${M.join(", ")})`}switch(w){case"contains":return typeof D=="string"?`${E} LIKE '%${D.replace(/'/g,"")}'`:`${E} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${E} LIKE '${D.replace(/'/g,"")}%'`:`${E} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${E} LIKE '%${D.replace(/'/g,"")}'`:`${E} LIKE '%${String(D)}'`;case"isNull":return`${E} IS NULL`;case"isNotNull":return`${E} IS NOT NULL`;default:return`${E} ${w} ${D}`}},A=I=>{const E=I.conditions.map(S),w=I.groups.map(V=>A(V)),D=[...E,...w].filter(Boolean);if(D.length===0)return"";const M=D.join(` ${I.logicalOperator} `),F=D.length>1?`(${M})`:M;return I.negate?`NOT ${F}`:F};return A(C)},P=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:i,isLoading:c,addCondition:u,addGroup:x,removeCondition:m,removeGroup:f,updateCondition:g,updateConditionFields:p,updateGroupOperator:h,updateGroupNegate:N,reorderConditions:b,reorderGroups:v,generateSQLPreview:k,hasAnyFilters:P}}function zi({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 qi=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function $i({value:s,onValueChange:a,availableFields:r,placeholder:o="Select field",className:d="w-64"}){const[c,i]=y.useState(!1),l=y.useMemo(()=>{const u={};return r.forEach(x=>{const m=qi(x);u[m]||(u[m]={}),u[m][x.entityId]||(u[m][x.entityId]=[]),u[m][x.entityId].push(x)}),u},[r]);return e.jsxs(t.Popover,{modal:!0,open:c,onOpenChange:i,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",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(zi,{children:[s.entityName,".",s.name]})}):o,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(l).map(([u,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"}),u]}),children:Object.entries(x).map(([m,f])=>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(f[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:f[0].entityName})]}),f.map((g,p)=>e.jsxs(n.CommandItem,{value:g.id,onSelect:()=>{a(g),i(!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)===g.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:g.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:g.description&&e.jsx("span",{children:g.description})})]})]},g.id+p))]},`${u}-${m}`))},u))})]})})]})}function Bs(s){var N;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:o}=n.useSemaphorContext(),d=t.useEditorStore(b=>b.card.config),c=d==null?void 0:d.joinPlan,i={...s,alias:s.name,label:"value",role:"groupby"},l={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},u={...i,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[i],metricColumns:[l],sortByColumns:[u]},m=((N=a.dataSource)==null?void 0:N.connectionId)||a.connectionId,{data:f,isPending:g,error:p}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:m,cardConfig:x,cardDataSource:a.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((f==null?void 0:f.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:g,error:p}}function Ki({field:s,selected:a,onChange:r,placeholder:o="Select items...",className:d}){const[c,i]=tr.useState(!1),{filterValues:l}=Bs(s),u=m=>{r(a.filter(f=>f!==m))},x=m=>{a.includes(m)?r(a.filter(f=>f!==m)):r([...a,m])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:c,onOpenChange:i,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(m=>{const f=l.find(g=>g.value===m);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[f==null?void 0:f.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:g=>{g.key==="Enter"&&u(m)},onMouseDown:g=>{g.preventDefault(),g.stopPropagation()},onClick:g=>{g.stopPropagation(),u(m)},children:e.jsx(ae.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:o})}),e.jsx(ae.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:l.map((m,f)=>e.jsxs(n.CommandItem,{onSelect:()=>x(m.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+f))})]})]})})]})})}function Ui({field:s,value:a,onChange:r,placeholder:o="Select value...",className:d}){const{filterValues:c,isPending:i,error:l}=Bs(s);return i?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..."]}):l?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:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:o,children:a})}),e.jsx(t.SelectContent,{children:c.map((u,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+x))})]})}function Gi({value:s,operator:a,onChange:r,className:o}){var p,h,N;const{tokenProps:d}=n.useSemaphorContext(),c=((h=(p=d==null?void 0:d.params)==null?void 0:p.calendarContext)==null?void 0:h.tz)||((N=d==null?void 0:d.params)==null?void 0:N.timezone),i=c||Intl.DateTimeFormat().resolvedOptions().timeZone,l=a==="between"||a==="not between",u=y.useMemo(()=>{if(!(!s||!l)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,v=s[1]?new Date(s[1]):void 0;if(b&&v)return{from:b,to:v}}},[s,l]),x=y.useMemo(()=>{if(!s||l)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const v=new Date(b);if(!isNaN(v.getTime()))return v},[s,l]),m=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,i):t.startOfDayInTimezone(b,i),f=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},g=b=>{if(!b){r("");return}const v=m(b);r(v.toISOString())};return e.jsx(n.DateRangePicker,{value:l?u:void 0,selectionMode:l?"range":"single",singleValue:l?void 0:x,onChange:f,onSingleChange:g,timezone:c,showRelativeTab:l,className:o,placeholder:"Select date..."})}const _s=["contains","startsWith","endsWith","like","not like"],Hi=["=","!=",">",">=","<","<=",..._s,"in","not in","isNull","isNotNull"],Qi=["=","!=",..._s,"in","not in","isNull","isNotNull"],Wi=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Yi=["=","!=","isNull","isNotNull"],Ji=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Xi={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",like:"Like","not like":"Not Like",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function Zn(s){return Xi[s]||t.titleCase(s)}function Zi(s){switch(s){case"string":return Qi;case"number":return Wi;case"boolean":return Yi;case"date":return Ji;default:return Hi}}function ka({condition:s,index:a,groupId:r,groupLogicalOperator:o,onUpdateCondition:d,onRemoveCondition:c,onUpdateGroupOperator:i,availableFields:l,updateConditionFields:u}){const{attributes:x,listeners:m,setNodeRef:f,transform:g,transition:p,isDragging:h}=n.useSortable({id:s.id}),{isPending:N,error:b}=Bs(s.field),v={transform:n.CSS.Transform.toString(g),transition:p};return e.jsxs("div",{ref:f,style:v,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${h?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...m,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:o,onValueChange:k=>i(r,k),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($i,{value:s.field,onValueChange:k=>{const P=k,C=t.getDataType(P.dataType)==="date";u(r,s.id,{field:P,value:"",operator:C?"between":"="})},availableFields:l,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:k=>{k==="in"||k==="not in"?u(r,s.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?u(r,s.id,{operator:k,value:null}):k==="between"||k==="not between"?u(r,s.id,{operator:k,value:[]}):u(r,s.id,{operator:k,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?Zn(s.operator):""})}),e.jsx(t.SelectContent,{children:Zi(t.getDataType(s.field.dataType)).map(k=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:k,children:Zn(k)},k))})]}),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"?N?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(Ki,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(k=>typeof k=="string")?s.value:[],onChange:k=>u(r,s.id,{value:k}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):_s.includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:k=>u(r,s.id,{value:k.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Ui,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:k=>u(r,s.id,{value:k}),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:k=>u(r,s.id,{value:k==="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(Gi,{value:s.value,operator:s.operator,onChange:k=>u(r,s.id,{value:k}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:k=>d(r,s.id,"value",k.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(ae.X,{className:"h-3 w-3"})})]})}function ec({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:d,onRemoveGroup:c,onUpdateCondition:i,onUpdateField:l,onRemoveCondition:u,onReorderConditions:x,onReorderGroups:m,onAddCondition:f,onAddGroup:g,availableFields:p,renderFilterGroup:h,updateConditionFields:N}){const{attributes:b,listeners:v,setNodeRef:k,transform:P,transition:C,isDragging:S}=n.useSortable({id:s.id}),A={transform:n.CSS.Transform.toString(P),transition:C},I=w=>{const{active:D,over:M}=w;if(M&&D.id!==M.id){const F=s.conditions.findIndex(R=>R.id===D.id),V=s.conditions.findIndex(R=>R.id===M.id);F!==-1&&V!==-1&&x(s.id,F,V)}},E=w=>{const{active:D,over:M}=w;if(M&&D.id!==M.id&&r){const F=s.groups.findIndex(R=>R.id===D.id),V=s.groups.findIndex(R=>R.id===M.id);F!==-1&&V!==-1&&m(r,F,V)}};return e.jsxs("div",{ref:k,style:A,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${S?"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,...v,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:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:w=>o(s.id,w),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:I,children:e.jsx(n.SortableContext,{items:s.conditions.map(w=>w.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((w,D)=>e.jsx(ka,{condition:w,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:i,onUpdateField:l,onRemoveCondition:u,onUpdateGroupOperator:o,availableFields:p,updateConditionFields:N},w.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:E,children:e.jsx(n.SortableContext,{items:s.groups.map(w=>w.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(w=>h(w,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:()=>f(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:()=>g(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function tc({filters:s,availableFields:a,onSave:r,onClearAll:o,onCancel:d}){const{currentFilters:c,availableFields:i,isLoading:l,addCondition:u,addGroup:x,removeCondition:m,removeGroup:f,updateCondition:g,updateConditionFields:p,updateGroupOperator:h,updateGroupNegate:N,reorderConditions:b,reorderGroups:v,generateSQLPreview:k,hasAnyFilters:P,setCurrentFilters:C}=_i({initialFilters:s,availableFields:a}),S=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[A,I]=y.useState(!1),E=(M,F,V)=>{const R=j=>j.id===M?{...j,conditions:j.conditions.map(T=>T.id===F?{...T,field:V,dataType:V.dataType}:T)}:{...j,groups:j.groups.map(R)};C(R(c))},w=(M,F=0,V)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:j,over:T}=R;if(T&&j.id!==T.id){const L=M.conditions.findIndex(B=>B.id===j.id),O=M.conditions.findIndex(B=>B.id===T.id);L!==-1&&O!==-1&&b(M.id,L,O)}},children:e.jsx(n.SortableContext,{items:M.conditions.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:M.conditions.map((R,j)=>e.jsx(ka,{condition:R,index:j,groupId:M.id,groupLogicalOperator:M.logicalOperator,onUpdateCondition:g,onUpdateField:E,onRemoveCondition:m,onUpdateGroupOperator:h,availableFields:i,updateConditionFields:p},R.id))})}),e.jsx(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragEnd:R=>{const{active:j,over:T}=R;if(T&&j.id!==T.id){const L=M.groups.findIndex(B=>B.id===j.id),O=M.groups.findIndex(B=>B.id===T.id);L!==-1&&O!==-1&&v(M.id,L,O)}},children:e.jsx(n.SortableContext,{items:M.groups.map(R=>R.id),strategy:n.verticalListSortingStrategy,children:M.groups.map(R=>w(R,F+1,M.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>u(M.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),A&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(M.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},M.id):e.jsx(ec,{group:M,depth:F,parentGroupId:V,onUpdateGroupOperator:h,onUpdateGroupNegate:N,onRemoveGroup:f,onUpdateCondition:g,onUpdateField:E,onRemoveCondition:m,onReorderConditions:b,onReorderGroups:v,onAddCondition:u,onAddGroup:x,availableFields:i,renderFilterGroup:w,updateConditionFields:p},M.id),D=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:[l?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..."})]}):w(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:A,onCheckedChange:M=>I(M)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),P&&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:k(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),D>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(P?c:null),children:"Apply Filters"})]})]})}function sc({cardId:s,filters:a,onFiltersChange:r,onClearFilters:o,availableFields:d,isOpen:c,onOpenChange:i}){const l=x=>{r(s,x),i(!1)},u=()=>{o(s),i(!1)};return e.jsxs(n.Dialog,{modal:!1,open:c,onOpenChange:i,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(tc,{filters:a,availableFields:d,onSave:l,onCancel:()=>i(!1),onClearAll:u})]})]})}function nc({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:o}){var k,P;const[d,c]=y.useState(null),i=t.useEditorStore(C=>C.card),l=t.useEditorStore(C=>C.actions.updateCardConfig),u=t.useEditorStore(C=>C.actions.setCardPreferences),x=(k=i==null?void 0:i.config)==null?void 0:k.joinPlan,m=y.useCallback(C=>C.entityName===Za.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),f=(P=i==null?void 0:i.dataSource)==null?void 0:P.semanticDomainId,{data:g}=n.useJoinabilityMap(f),p=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],h=y.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||a.find(S=>S.id===C)?"source":r("groupBy").find(S=>S.id===C)?"groupBy":r("metrics").find(S=>S.id===C)?"metrics":r("pivotBy").find(S=>S.id===C)?"pivotBy":r("sortBy").find(S=>S.id===C)?"sortBy":r("detailColumns").find(S=>S.id===C)?"detailColumns":null,[a,r]),N=y.useCallback(C=>{c(C.active.id)},[]),b=y.useCallback(C=>{var M;const{active:S,over:A}=C;if(!A||!s){c(null);return}const I=S.id,E=A.id,w=h(I),D=h(E)||E;if(D==="sortBy"){if(w==="source"){const F=a.find(R=>R.id===I);if(!F){c(null);return}if(!(r("groupBy").some(R=>R.name===F.name&&R.qualifiedEntityName===F.qualifiedEntityName)||r("metrics").some(R=>R.name===F.name&&R.qualifiedEntityName===F.qualifiedEntityName)||r("detailColumns").some(R=>R.name===F.name&&R.qualifiedEntityName===F.qualifiedEntityName))){c(null);return}}else if(w==="pivotBy"){c(null);return}else if(w!=="groupBy"&&w!=="metrics"&&w!=="sortBy"&&w!=="detailColumns"){c(null);return}}if(w==="source"&&D==="sortBy"){const F=[...a].find(T=>T.id===I);if(!F){c(null);return}const V=r("sortBy");if(n.fieldAlreadyExists(F,V)){c(null);return}const R=n.validateFieldForChartType(F,"sortBy",i.type);if(!R.isValid){n.ue.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3}),c(null);return}const j=n.getNewField(F,"sortBy",V);c(null),o("sortBy",[...V,j]);return}if(w==="source"&&D!=="source"&&D!=="sortBy"){const F=[...a].find(B=>B.id===I);if(!F){c(null);return}const V=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],R=V.filter(B=>!m(B));if(R.length>0){const B=R[0].qualifiedEntityName;if(!B){c(null);return}if(B!==F.qualifiedEntityName&&!m(F)&&F.qualifiedEntityName)if(f&&(g!=null&&g.joinabilityMap)){if(n.calculateFieldState(F,{joinabilityMap:g.joinabilityMap,selectedFields:V,baseEntityName:(M=x==null?void 0:x.baseEntity)==null?void 0:M.name,datasetAliases:g.datasets}).state==="unreachable"){n.showJoinRequiredNotification(),c(null);return}}else{if(!x){n.showJoinRequiredNotification(),c(null);return}if(!n.areEntitiesJoined(B,F.qualifiedEntityName,x)){n.showJoinRequiredNotification(),c(null);return}}}const j=r(D);if(n.fieldAlreadyExists(F,j)){c(null);return}const T=n.validateFieldForChartType(F,D,i.type);if(!T.isValid){n.ue.error("Invalid Field Type",{description:T.reason,position:"top-center",duration:3e3}),c(null);return}const L=n.getNewField(F,D,j),O=[...j,L];if(c(null),o(D,O),D==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,L,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,l,s,O)}return}if(w&&D&&w!=="source"&&D!=="source"&&w!==D){const F=r(w),V=r(D),R=F.find(B=>B.id===I);if(!R){c(null);return}const j=n.validateFieldForChartType(R,D,i.type);if(!j.isValid){n.ue.error("Invalid Field Type",{description:j.reason,position:"top-center",duration:3e3}),c(null);return}const T=n.getNewField(R,D,V);if(c(null),D==="sortBy"){n.fieldAlreadyExists(R,V)||o(D,[...V,T]);return}const L=F.filter(B=>B.id!==I),O=[...V,T];if(o(w,L),o(D,O),D==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,T,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,l,s,O)}return}if(w&&D&&w===D&&w!=="source"){const F=r(w),V=F.findIndex(j=>j.id===I),R=F.findIndex(j=>j.id===E);if(V!==R){const j=n.arrayMove(F,V,R);o(w,j)}}c(null)},[s,a,r,o,h,x,f,g,m,i,l,u]),v=d?p.find(C=>C.id===d):null;return{activeId:d,activeField:v,handleDragStart:N,handleDragEnd:b}}function ac({activeView:s,onViewChange:a,splitViewEnabled:r}){const o=t.useEditorStore(u=>u.card),{config:d}=y.useContext(n.SemaphorContext).tokenProps,c=(d==null?void 0:d.showInfoTab)!==!1,i=()=>r?!1:t.getVisualizationMode(o)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(o.type),l=[{id:"chart",label:"Chart"}];return i()&&l.push({id:"table",label:"Results"}),c&&l.push({id:"info",label:"Info",icon:t.Info}),e.jsx(t.Tabs,{value:s,onValueChange:u=>a(u),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:l.map(u=>{const x=u.icon;return e.jsxs(t.TabsTrigger,{value:u.id,className:"gap-1.5 px-0 text-[13px]",children:[x&&e.jsx(x,{className:"h-3 w-3",strokeWidth:1.75}),u.label]},u.id)})})})}const rc=[{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 oc(){var u,x;const s=t.useEditorStore(m=>m.card),{updateRowLimit:a}=t.useEditorActions(),[r,o]=y.useState(!1),[d,c]=y.useState(""),i=m=>{if(m==="custom"){o(!0);return}o(!1),a(s.id,parseInt(m))},l=m=>{const f=m.target.value;c(f),f&&!isNaN(parseInt(f))&&a(s.id,parseInt(f))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:d,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(u=s.config)==null?void 0:u.rowLimit)==null?void 0:x.toString())||"100",onValueChange:i,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:rc.map(m=>e.jsx(t.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function lc({card:s,queryData:a,isLoading:r,isFetching:o,pagination:d,onPaginationChange:c,onSortChange:i,sortState:l,splitViewEnabled:u,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:m}){const f=y.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),g=t.getVisualizationMode(s)==="dynamic",p=e.jsx(Nt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(ba,{fallbackPreview:e.jsx(Nt,{}),records:f,title:s.title,isInspectorOpen:x,onInspectorOpenChange:m})});return g?u?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:p}),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||o)&&(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:f,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:d,onPaginationChange:c,isLoading:r||o,onSortChange:i,sortState:l})]})})]}):p:!u||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(Nt,{}):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(Nt,{})}),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||o)&&(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:f,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,paginationMetadata:d,onPaginationChange:c,isLoading:r||o,onSortChange:i,sortState:l})]})})]})}function ic(s,a){const[r,o]=y.useState(()=>{const d=localStorage.getItem(s);return d?JSON.parse(d):a});return y.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const cc="semaphor-split-view-enabled";function dc(){return ic(cc,!0)}function uc({card:s,effectiveCardType:a=s.type,queryResultColumns:r}){return t.supportsRegularTableSettings(a)?e.jsxs(n.Sheet,{modal:!1,children:[e.jsx(n.SheetTrigger,{asChild:!0,children:e.jsxs(n.IconButton,{tooltip:"Table settings",className:"h-7 w-auto gap-1.5 rounded-[5px] px-2 text-[12px] font-medium",buttonProps:{type:"button","aria-label":"Table settings"},children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{children:"Table Settings"})]})}),e.jsxs(n.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(n.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(n.SheetDescription,{className:"sr-only",children:"Configure table presentation and conditional formatting."}),e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:"Table settings"}),e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Settings apply to this table and document exports that reuse it."})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(Sa,{cardType:a,queryResultColumns:r,focusSection:"style"})})]})]}):null}function mc({className:s,visible:a}){const r=t.useDashboardStore(l=>l.selectedFrameId),o=n.useManagementStore(l=>l.selectedVisual),d=t.useEditorStore(l=>l.frame),i=!!!(d!=null&&d.visualId||o!=null&&o.id)&&!!r;return!a||i?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(Te.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function xc({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:o,columns:d}){var Ee,qe,$e;const c=t.useEditorStore(ce=>ce.card),i=t.useEditorStore(ce=>ce.editorContext),l=t.useEditorStore(ce=>ce.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),u=t.useEditorStore(ce=>ce.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ce=>ce.filterValues),m=t.useDashboardStore(ce=>ce.selectedSheetId),{updateCardConfig:f,setCard:g,updateCardInFrame:p,setShowAIDialog:h}=t.useEditorActions(),N=t.useEditorStore(ce=>ce.showAIDialog),b=t.useEditorStore(ce=>ce.isDevMode),v=t.useDashboardStore(ce=>ce.isVisualEditing),[k,P]=y.useState(!1),[C,S]=y.useState(!1),[A,I]=y.useState(!1),[E,w]=y.useState(null),{config:D}=y.useContext(n.SemaphorContext).tokenProps,M=(D==null?void 0:D.showInfoTab)!==!1,F=(D==null?void 0:D.showQueryDebugTools)!==!1,[V,R]=dc();t.useEditorStore(ce=>{var Re;return!!((Re=ce.card.customCardPreferences)!=null&&Re.url)});const T=t.getVisualizationMode(c)==="dynamic",L=(i==null?void 0:i.type)==="documentSection",O=Te.useEffectiveEditorCardType(),{data:B,errorMessage:z,isLoading:_,isFetching:q,errorSql:G,pagination:H,refetch:$,comparisonMetadata:W,queryRequestPayload:Q,resolvedPrimaryDateField:se}=n.useEditorCardQuery(o),ue=y.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),pe=y.useMemo(()=>!q&&ue.length>0?Object.keys(ue[0]):[],[q,ue]),[ge,ve]=y.useState(!1);y.useEffect(()=>{q||ve(!1)},[q]);const Pe=()=>{const ce=!V;ce&&s==="table"&&a("chart"),R(ce)},Ve=(ce,Re)=>{const we={...o,paginationConfig:{page:ce+1,pageSize:Re}};g(we),p(we)},ee=ce=>{if(!c.config)return;const Re=n.sortStateToSortByColumns(ce,c.config.metricColumns,c.config.groupByColumns,c.config.detailColumns);f(c.id,{...c.config,sortByColumns:Re})},xe=y.useMemo(()=>{var ce;return n.sortByColumnsToSortState((ce=c.config)==null?void 0:ce.sortByColumns)},[(Ee=c.config)==null?void 0:Ee.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":N&&v}),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"&&N&&!L&&!T&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Co,{variant:b?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(ac,{activeView:s,onViewChange:a,splitViewEnabled:V}),e.jsx(oc,{})]}),O==="kpi"&&e.jsx(mc,{visible:!0,className:"self-center"}),W&&c.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:W,variant:"compact"}),N&&e.jsx(Te.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:o.id,cardFilters:(qe=o.config)==null?void 0:qe.filters,cardFilterCount:n.getFilterCount((($e=o.config)==null?void 0:$e.filters)||null),onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:l,sheetId:m||"",removeInlineFilterValue:ce=>u(o.id,ce),resolvedPrimaryDateField:se}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:_||q,onClick:()=>{ve(!0),$()},children:e.jsx(na,{className:t.cn("h-3.5 w-3.5",{"animate-spin":ge})})}),s==="chart"&&e.jsx(uc,{card:o,effectiveCardType:O,queryResultColumns:pe}),s==="chart"&&!T&&e.jsx(ga,{showInlineFilters:!1,showControls:!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:Pe,children:[V?e.jsx(or,{className:"mr-2 h-4 w-4"}):e.jsx(vr,{className:"mr-2 h-4 w-4"}),V?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(ja,{onCustomize:()=>I(!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(lc,{card:o,queryData:B,isLoading:_,isFetching:q,pagination:H,onPaginationChange:Ve,onSortChange:ee,sortState:xe,splitViewEnabled:V,isDynamicInspectorOpen:A,onDynamicInspectorOpenChange:I})}),s==="table"&&(B==null?void 0:B.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:[(_||q)&&(B==null?void 0:B.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:o,data:ue,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:W,paginationMetadata:H,onPaginationChange:Ve,isLoading:_||q,onSortChange:ee,sortState:xe})]}),s==="info"&&M&&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:z?e.jsx(os,{error:z,errorSql:G,showCardDetails:!0,debugPayloads:F?{queryRequest:Q,queryResponse:B,columns:d,dashboardFilters:x}:void 0,onSendFeedback:()=>{const ce=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:c.config,dataSource:o.dataSource,dashboardFilters:x,errorMessage:z,errorSql:G,generatedSql:B==null?void 0:B.sql});w(ce),S(!0)},onOpenInEditor:()=>{h(!0),setTimeout(()=>{const ce=t.useEditorStore.getState().actions;ce.setIsDevMode(!0),ce.setCardSql(G||""),setTimeout(()=>{ce.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(va,{sql:B.sql,showCardDetails:!0,debugPayloads:F?{queryRequest:Q,queryResponse:B,columns:d,dashboardFilters:x}:void 0})})})]}),E&&e.jsx(n.FeedbackDialog,{open:C,onOpenChange:S,feedbackData:E})]})})}function hc({activeField:s}){const[a,r]=y.useState(!0);if(y.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=!!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:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const pc=()=>{const s=console.error;console.error=(...o)=>{o.length>0&&typeof o[0]=="string"&&o[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,o)};const a=o=>{if(o.message&&(o.message.includes("ResizeObserver loop completed with undelivered notifications")||o.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),o.stopPropagation(),!1},r=o=>{var d;if((d=o.reason)!=null&&d.message&&(o.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||o.reason.message.includes("ResizeObserver loop limit exceeded")))return o.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 fc({column:s,isSelected:a,onSelect:r,availableFields:o,width:d,onWidthChange:c}){var B,z,_;const i=t.useEditorStore(q=>q.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:x,updateFilters:m}=t.useEditorActions(),[f,g]=y.useState(!1),[p,h]=y.useState(!1),N=y.useRef(null),b=y.useCallback(q=>{q.preventDefault(),q.stopPropagation(),h(!0),N.current={startX:q.clientX,startWidth:d||150};const G=$=>{if(!N.current)return;const W=$.clientX-N.current.startX,Q=Math.max(80,N.current.startWidth+W);c==null||c(s.id,Q)},H=()=>{h(!1),N.current=null,document.removeEventListener("mousemove",G),document.removeEventListener("mouseup",H)};document.addEventListener("mousemove",G),document.addEventListener("mouseup",H)},[d,s.id,c]),v=(B=i==null?void 0:i.config)==null?void 0:B.filters,k=(z=v==null?void 0:v.conditions)==null?void 0:z.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),P=q=>{q?m(i.id,q):l(i.id,{filters:void 0})},{attributes:C,listeners:S,setNodeRef:A,transform:I,transition:E,isDragging:w}=n.useSortable({id:s.id}),D={transform:n.CSS.Transform.toString(I),transition:E},M=t.getDataType(s.dataType),F=gc(M),V=()=>{var H;const q=((H=i==null?void 0:i.config)==null?void 0:H.sortByColumns)||[],G=q.findIndex($=>$.name===s.name);if(G!==-1){const $=[...q];$[G]={...$[G],direction:"asc"},l(i.id,{sortByColumns:$})}else l(i.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var H;const q=((H=i==null?void 0:i.config)==null?void 0:H.sortByColumns)||[],G=q.findIndex($=>$.name===s.name);if(G!==-1){const $=[...q];$[G]={...$[G],direction:"desc"},l(i.id,{sortByColumns:$})}else l(i.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},j=()=>{var H;const q=((H=i==null?void 0:i.config)==null?void 0:H.groupByColumns)||[];if(!q.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...q,$]})}},T=q=>{var $;const G=(($=i==null?void 0:i.config)==null?void 0:$.metricColumns)||[];if(!G.some(W=>W.name===s.name&&W.aggregate===q)){const W={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q};l(i.id,{metricColumns:[...G,W]})}},L=()=>{s.role==="groupby"?u(i.id,s.id):s.role==="metric"&&x(i.id,s.id)},O={...D,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:A,style:O,className:t.cn("group relative border-r border-border bg-background px-1 py-0",w&&"opacity-50",a&&"bg-primary/10",p&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...S,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(F,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),k&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(ae.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>g(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",k&&"text-primary")}),k?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:V,children:[e.jsx(nr,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:R,children:[e.jsx(sr,{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:()=>T("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>T("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:j,children:[e.jsx(n.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(As,{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:L,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",p&&"bg-primary")}),e.jsx(Ia,{open:f,onOpenChange:g,availableFields:o.length>0?o:[s],existingFilters:v,editingCondition:k?(_=v==null?void 0:v.conditions)==null?void 0:_.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:P})]})}function gc(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function bc({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:o=[],filterableFields:d=o}){var w,D,M,F;const c=t.useEditorStore(V=>V.card),{updateCardConfig:i}=t.useEditorActions(),[l,u]=y.useState(null),[x,m]=y.useState({}),[f,g]=y.useState(!1),p=y.useMemo(()=>{var j,T;const V=((j=c==null?void 0:c.config)==null?void 0:j.groupByColumns)||[],R=((T=c==null?void 0:c.config)==null?void 0:T.metricColumns)||[];return[...V,...R]},[(w=c==null?void 0:c.config)==null?void 0:w.groupByColumns,(D=c==null?void 0:c.config)==null?void 0:D.metricColumns]),h=y.useMemo(()=>{const V=new Set(p.map(R=>`${R.qualifiedEntityName}.${R.name}`));return o.filter(R=>!V.has(`${R.qualifiedEntityName}.${R.name}`))},[o,p]),{data:N,isLoading:b}=n.useEditorCardQuery(c),v=(N==null?void 0:N.records)||[],k=y.useCallback((V,R)=>{m(j=>({...j,[V]:R}))},[]),P=y.useCallback(V=>{var L,O;const R=t.getDataType(V.dataType),j=((L=c==null?void 0:c.config)==null?void 0:L.groupByColumns)||[],T=((O=c==null?void 0:c.config)==null?void 0:O.metricColumns)||[];if(R==="number"){const B={...V,id:`metric-${V.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};i(c.id,{metricColumns:[...T,B]})}else{const B={...V,id:`groupby-${V.id}-${Date.now()}`,role:"groupby"};i(c.id,{groupByColumns:[...j,B]})}g(!1)},[(M=c==null?void 0:c.config)==null?void 0:M.groupByColumns,(F=c==null?void 0:c.config)==null?void 0:F.metricColumns,c.id,i]),C=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),S=V=>{u(V.active.id)},A=V=>{const{active:R,over:j}=V;if(u(null),!j||R.id===j.id)return;const T=p.findIndex(O=>O.id===R.id),L=p.findIndex(O=>O.id===j.id);if(T!==-1&&L!==-1){const O=n.arrayMove(p,T,L),B=O.filter(_=>_.role==="groupby"),z=O.filter(_=>_.role==="metric");i(c.id,{groupByColumns:B,metricColumns:z})}},I=l?p.find(V=>V.id===l):null,E=V=>{let R="";for(;V>=0;)R=String.fromCharCode(V%26+65)+R,V=Math.floor(V/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"})}):p.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(n.DndContext,{sensors:C,collisionDetection:n.closestCenter,onDragStart:S,onDragEnd:A,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(n.SortableContext,{items:p.map(V=>V.id),strategy:n.horizontalListSortingStrategy,children:p.map((V,R)=>e.jsx("th",{style:{width:x[V.id]?`${x[V.id]}px`:void 0,minWidth:x[V.id]?`${x[V.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:E(R)},`letter-${V.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:p.map(V=>V.id),strategy:n.horizontalListSortingStrategy,children:p.map(V=>e.jsx(fc,{column:V,isSelected:(s==null?void 0:s.id)===V.id,onSelect:()=>a(V),availableFields:d,width:x[V.id],onWidthChange:k},V.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:f,onOpenChange:g,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:h.map(V=>{const R=t.getDataType(V.dataType),j=R==="number"?n.Hash:R==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:V.label||V.name,onSelect:()=>P(V),children:[e.jsx(j,{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:V.label||V.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:V.entityName})]})]},V.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):v.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):v.slice(0,100).map((V,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}),p.map(j=>{const T=V[j.name]??V[j.label??""];return e.jsx("td",{style:{width:x[j.id]?`${x[j.id]}px`:void 0,minWidth:x[j.id]?`${x[j.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===j.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:jc(T,j)})},`${R}-${j.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(n.DragOverlay,{children:I&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:I.label||I.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(v.length,100)," of ",v.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function jc(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 vc({entityGroups:s,isLoading:a=!1}){var P,C;const r=t.useEditorStore(S=>S.card),{updateCardConfig:o,removeGroupByColumn:d,removeMetricColumn:c}=t.useEditorActions(),[i,l]=y.useState(!0),[u,x]=y.useState(""),[m,f]=y.useState(new Set),g=((P=r==null?void 0:r.config)==null?void 0:P.groupByColumns)||[],p=((C=r==null?void 0:r.config)==null?void 0:C.metricColumns)||[],h=S=>{const A=new Set(m);A.has(S)?A.delete(S):A.add(S),f(A)},N=S=>g.some(A=>A.name===S.name&&A.qualifiedEntityName===S.qualifiedEntityName)||p.some(A=>A.name===S.name&&A.qualifiedEntityName===S.qualifiedEntityName),b=(S,A)=>{if(A)if(t.getDataType(S.dataType)==="number"){const E={...S,id:`metric-${S.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(r.id,{metricColumns:[...p,E]})}else{const E={...S,id:`groupby-${S.id}-${Date.now()}`,role:"groupby"};o(r.id,{groupByColumns:[...g,E]})}else{const I=g.findIndex(w=>w.name===S.name&&w.qualifiedEntityName===S.qualifiedEntityName),E=p.findIndex(w=>w.name===S.name&&w.qualifiedEntityName===S.qualifiedEntityName);I!==-1&&d(r.id,g[I].id),E!==-1&&c(r.id,p[E].id)}},v=S=>{if(!u)return S;const A=u.toLowerCase();return S.filter(I=>I.name.toLowerCase().includes(A)||I.label&&I.label.toLowerCase().includes(A))},k=S=>{switch(t.getDataType(S)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>l(!1),title:"Close panel",children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ue.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:u,onChange:S=>x(S.target.value),className:"h-8 pl-8 text-sm"})]})}),(g.length>0||p.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[g.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(Ue.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.Rows3,{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:g.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:g.map(S=>{const A=k(S.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(A,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.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:()=>d(r.id,S.id),children:e.jsx(ae.X,{className:"h-3 w-3"})})]},S.id)})})})]}),p.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(Ue.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:p.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(S=>{const A=k(S.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(A,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.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,S.id),children:e.jsx(ae.X,{className:"h-3 w-3"})})]},S.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(S=>{const A=v(S.columns);if(A.length===0)return null;const I=m.has(S.entityId)||u.length>0;return e.jsxs(n.Collapsible,{open:I,onOpenChange:()=>h(S.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(Ue.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",I&&"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:S.label||S.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:A.map(E=>{const w=k(E.dataType),D=N(E);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",D&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:D,onCheckedChange:M=>b(E,M),className:"h-3.5 w-3.5"}),e.jsx(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name})]},E.id)})})})]},S.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:()=>l(!0),title:"Open panel",children:e.jsx(pr,{className:"h-4 w-4"})})})}const yc=[{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 Nc({value:s,onChange:a,onSubmit:r,onCancel:o,selectedColumn:d,availableColumns:c}){const[i,l]=y.useState(!1),[u,x]=y.useState("column"),m=y.useRef(null);y.useEffect(()=>{const h=N=>{N.key==="Escape"&&s?o():N.key==="Enter"&&s&&!i&&r(s)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[s,o,r,i]);const f=h=>{const N=`[${h.label||h.name}]`,b=m.current;if(b){const v=b.selectionStart||0,k=b.selectionEnd||0,P=s.slice(0,v)+N+s.slice(k);a(P),setTimeout(()=>{b.setSelectionRange(v+N.length,v+N.length),b.focus()},0)}else a(s+N);l(!1)},g=h=>{const N=m.current;if(N){const b=N.selectionStart||0,v=N.selectionEnd||0,k=s.slice(0,b)+h.syntax+s.slice(v);a(k),setTimeout(()=>{N.setSelectionRange(b+h.name.length+1,b+h.syntax.length-1),N.focus()},0)}else a(s+h.syntax);l(!1)},p=h=>{switch(t.getDataType(h)){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:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:i&&u==="function",onOpenChange:h=>{l(h),h&&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(jr,{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:yc.map(h=>e.jsx(n.CommandItem,{value:h.name,onSelect:()=>g(h),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:h.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:h.syntax})]})},h.name))})]})]})})]}),e.jsxs(t.Popover,{open:i&&u==="column",onOpenChange:h=>{l(h),h&&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(ae.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(h=>{const N=p(h.dataType);return e.jsxs(n.CommandItem,{value:h.label||h.name,onSelect:()=>f(h),children:[e.jsx(N,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:h.label||h.name})]},h.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:m,value:s,onChange:h=>a(h.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:o,title:"Cancel (Esc)",children:e.jsx(ae.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 Cc({className:s}){var p,h,N,b;const a=t.useEditorStore(v=>v.card),[r,o]=y.useState(null),[d,c]=y.useState(""),{columns:i=[],columnGroups:l=[],isLoading:u}=n.useColumns(),{valuePickFilterableFields:x=[]}=n.useFilterableFields();(p=a==null?void 0:a.config)!=null&&p.groupByColumns,(h=a==null?void 0:a.config)!=null&&h.metricColumns,(N=a==null?void 0:a.config)!=null&&N.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const m=v=>{o(v),c(v?`[${v.label||v.name}]`:"")},f=v=>{console.log("Formula submitted:",v),c(""),o(null)},g=()=>{c(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Nc,{value:d,onChange:c,onSubmit:f,onCancel:g,selectedColumn:r,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(bc,{selectedColumn:r,onColumnSelect:m,isLoading:u,sourceFields:i,filterableFields:x})}),e.jsx(vc,{entityGroups:l,isLoading:u})]})]})}function Sc(){var B,z;const[s,a]=y.useState("chart"),[r,o]=y.useState(!1),[d,c]=y.useState(!0),[i,l]=y.useState(!0),u=t.useEditorStore(_=>_.showAIDialog),x=t.useDashboardStore(_=>_.isVisualEditing),{setCardType:m}=t.useEditorActions(),f=t.useEditorStore(_=>_.card.type);y.useEffect(()=>pc(),[]);const g=_=>{m(_)},p=t.useEditorStore(_=>_.frame),h=t.useEditorStore(_=>_.card);t.useEditorStore(_=>_.activeTabCardId),t.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:N,removeCard:b,updateCard:v,setActiveCard:k,updateFilters:P}=t.useEditorActions(),{columnFields:C=[],scopedFields:S=[],filterableFields:A=[]}=n.useFilterableFields(),I=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),E=h,{getFieldsForContainer:w,setFieldsForContainer:D}=n.useFieldManagement(E),{activeField:M,handleDragStart:F,handleDragEnd:V}=nc({activeCardId:p.activeCardId,sourceFields:S,getFieldsForContainer:w,setFieldsForContainer:D}),R=(_,q)=>{q&&P(_,q)},j=_=>{var q;v(_,{config:{...(q=p.cards.find(G=>G.id===_))==null?void 0:q.config,filters:void 0}})},T=A,L=_=>{if(!_)return 0;let q=_.conditions.length;return _.groups.forEach(G=>{q+=L(G)}),q},O=L(((B=E==null?void 0:E.config)==null?void 0:B.filters)||null);return e.jsxs(n.DndContext,{sensors:I,collisionDetection:n.closestCenter,onDragStart:F,onDragEnd:V,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(la,{isVisible:d,onToggleVisibility:()=>c(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:f==="tableBuilder"?e.jsx(Cc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!u&&e.jsx(Bi,{selectedChart:f,onChartChange:g,groupByFields:w("groupBy"),pivotByFields:w("pivotBy"),metricsFields:w("metrics"),sortByFields:w("sortBy"),detailFields:w("detailColumns"),activeField:M,isVisible:i,onToggleVisibility:()=>l(!i)}),e.jsx(xc,{selectedChart:f,activeView:s,onViewChange:a,onFiltersClick:()=>o(!0),filterCount:O,activeCard:E,columns:C,getFieldsForContainer:w,cards:p.cards,activeCardId:p.activeCardId,addCard:N,setActiveCard:k})]})}),!d&&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"})})})]}),E&&e.jsx(sc,{cardId:E.id,filters:((z=E.config)==null?void 0:z.filters)||null,onFiltersChange:R,onClearFilters:j,availableFields:T,isOpen:r,onOpenChange:o}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(hc,{activeField:M||null})})]})}function wc({authToken:s,onSave:a,onClose:r}){const o=y.useRef(null),d=t.useEditorStore(I=>I.showAIDialog),c=t.useEditorStore(I=>I.isDevMode),i=n.useAssistantLayoutStore(I=>I.setFullscreen),l=n.useAssistantLayoutStore(I=>I.setPanelOpen),u=n.useAssistantLayoutStore(I=>I.setContainer),x=n.useAssistantPanel("editor"),m=n.useFullscreenAssistant(),f=n.useAssistantContainer("editor"),g=m==="editor",p=n.useDashboardAppearance(),h=y.useCallback(I=>{u("editor",I)},[u]),{setAuthToken:N}=t.useDashboardActions(),{setShowAIDialog:b,setOnSave:v,setOnClose:k}=t.useEditorActions(),{setActiveAssistantType:P}=t.useAIActions();y.useEffect(()=>{a&&v(a),r&&k(r)},[a,v,r,k]),y.useEffect(()=>{s&&s.accessToken&&N(s)},[s,N]),y.useEffect(()=>{var I,E;d?((I=o.current)==null||I.resize(40),l("editor",!0),P("editor")):((E=o.current)==null||E.resize(0),l("editor",!1),m==="editor"&&i(null),P(null))},[d,l,P,i,m]);function C(I){var E;I<1?(b(!1),l("editor",!1),m==="editor"&&i(null),P(null),(E=o.current)==null||E.resize(0)):(d||(b(!0),P("editor")),x.isOpen||l("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(la,{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",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(pi,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:C,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Jn,{isFullscreen:g,onFullscreenChange:I=>i(I?"editor":null),fullscreenContainer:f})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!g&&"pointer-events-none")})]})]})}function A(){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",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Sc,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:C,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Jn,{isFullscreen:g,onFullscreenChange:I=>i(I?"editor":null),fullscreenContainer:f})})})]}),e.jsx("div",{ref:h,className:t.cn("absolute inset-0",!g&&"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:p.dashboardContainerStyle,children:S()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:p.dashboardContainerStyle,children:A()})})}function Tc(){t.useDashboardStore(p=>p.selectedCardId);const s=t.useDashboardStore(p=>p.selectedSheetId),a=t.useDashboardStore(p=>p.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(p=>p.actions),d=t.useEditorStore(p=>p.editorContext),{clearEditorContext:c}=t.useEditorStore(p=>p.actions),i=n.useDashboardAppearance(),l=t.useDashboardStore(p=>p.isVisualEditing),u=t.useDashboardStore(p=>p.actions.updateFrame),x=t.useDashboardStore(p=>p.actions.updateDocumentSectionCard),m=n.useResolveExistingFrameSemanticExecutionPayload();async function f(p){var k,P,C;if((d==null?void 0:d.type)==="documentSection"){const S=n.getDocumentSectionEditorCard(p,d.cardId);if(!S){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(S)){n.ue.error("Document table sections support Table and Pivot Table");return}x(d.sheetId,d.sectionId,S,{calculatedFields:p.calculatedFields}),c(),r(!1);return}const h=s?(k=a==null?void 0:a.sheets)==null?void 0:k.some(S=>{var A;return S.id===s&&((A=S.frames)==null?void 0:A.some(I=>I.id===p.id))}):!1,N=(C=(P=a==null?void 0:a.sheets)==null?void 0:P.find(S=>{var A;return(A=S.frames)==null?void 0:A.some(I=>I.id===p.id)}))==null?void 0:C.id,b=h?s:N||null;if(!b)return;const v=t.findDashboardFrameById(a,p.id);try{const S=await m(p,{previousFrame:v});u(b,p,{semanticExecutionPayload:S}),s!==b&&o(b),r(!1)}catch(S){console.error("Failed to resolve semantic metadata on save:",S),n.ue.error(S instanceof Error?S.message:"Failed to resolve semantic metadata for this visual")}}function g(){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":!l}),style:i.dashboardContainerStyle,children:e.jsx(wc,{onSave:f,onClose:g})})}exports.default=Tc;