react-semaphor 0.0.628 → 0.0.630

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.
@@ -1,365 +0,0 @@
1
- "use strict";const e=require("react/jsx-runtime"),s=require("./index-DlGdDEyt.js"),A=require("react");require("react-dom");function ta(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ee=ta(A);/**
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 aa=s.createLucideIcon("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/**
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 na=s.createLucideIcon("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/**
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 ra=s.createLucideIcon("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/**
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 la=s.createLucideIcon("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/**
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 oa=s.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
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 ia=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
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 ca=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
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 da=s.createLucideIcon("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/**
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 ua=s.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
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 Ss=s.createLucideIcon("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
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 Vs=s.createLucideIcon("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/**
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 We=s.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
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 ma=s.createLucideIcon("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
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 ha=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
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 Pe=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
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 xa=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
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 pa=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
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 fa=s.createLucideIcon("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
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 ga=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
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 tt=s.createLucideIcon("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/**
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 ja=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
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 ba=s.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
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 ya=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
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 va=s.createLucideIcon("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
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 Na=s.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
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 Ca=s.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
132
- * @license lucide-react v0.453.0 - ISC
133
- *
134
- * This source code is licensed under the ISC license.
135
- * See the LICENSE file in the root directory of this source tree.
136
- */const rs=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
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 Sa=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
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 De=s.createLucideIcon("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
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 wa=s.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
152
- * @license lucide-react v0.453.0 - ISC
153
- *
154
- * This source code is licensed under the ISC license.
155
- * See the LICENSE file in the root directory of this source tree.
156
- */const Da=s.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
157
- * @license lucide-react v0.453.0 - ISC
158
- *
159
- * This source code is licensed under the ISC license.
160
- * See the LICENSE file in the root directory of this source tree.
161
- */const ka=s.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
162
- * @license lucide-react v0.453.0 - ISC
163
- *
164
- * This source code is licensed under the ISC license.
165
- * See the LICENSE file in the root directory of this source tree.
166
- */const Ta=s.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
167
- * @license lucide-react v0.453.0 - ISC
168
- *
169
- * This source code is licensed under the ISC license.
170
- * See the LICENSE file in the root directory of this source tree.
171
- */const at=s.createLucideIcon("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/**
172
- * @license lucide-react v0.453.0 - ISC
173
- *
174
- * This source code is licensed under the ISC license.
175
- * See the LICENSE file in the root directory of this source tree.
176
- */const Ea=s.createLucideIcon("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
177
- * @license lucide-react v0.453.0 - ISC
178
- *
179
- * This source code is licensed under the ISC license.
180
- * See the LICENSE file in the root directory of this source tree.
181
- */const Ia=s.createLucideIcon("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/**
182
- * @license lucide-react v0.453.0 - ISC
183
- *
184
- * This source code is licensed under the ISC license.
185
- * See the LICENSE file in the root directory of this source tree.
186
- */const $e=s.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
187
- * @license lucide-react v0.453.0 - ISC
188
- *
189
- * This source code is licensed under the ISC license.
190
- * See the LICENSE file in the root directory of this source tree.
191
- */const Aa=s.createLucideIcon("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
192
- * @license lucide-react v0.453.0 - ISC
193
- *
194
- * This source code is licensed under the ISC license.
195
- * See the LICENSE file in the root directory of this source tree.
196
- */const Ma=s.createLucideIcon("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/**
197
- * @license lucide-react v0.453.0 - ISC
198
- *
199
- * This source code is licensed under the ISC license.
200
- * See the LICENSE file in the root directory of this source tree.
201
- */const La=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
202
- * @license lucide-react v0.453.0 - ISC
203
- *
204
- * This source code is licensed under the ISC license.
205
- * See the LICENSE file in the root directory of this source tree.
206
- */const Ra=s.createLucideIcon("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/**
207
- * @license lucide-react v0.453.0 - ISC
208
- *
209
- * This source code is licensed under the ISC license.
210
- * See the LICENSE file in the root directory of this source tree.
211
- */const Oa=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
212
- * @license lucide-react v0.453.0 - ISC
213
- *
214
- * This source code is licensed under the ISC license.
215
- * See the LICENSE file in the root directory of this source tree.
216
- */const Us=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
217
- * @license lucide-react v0.453.0 - ISC
218
- *
219
- * This source code is licensed under the ISC license.
220
- * See the LICENSE file in the root directory of this source tree.
221
- */const Gs=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
222
- * @license lucide-react v0.453.0 - ISC
223
- *
224
- * This source code is licensed under the ISC license.
225
- * See the LICENSE file in the root directory of this source tree.
226
- */const Ba=s.createLucideIcon("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
227
- * @license lucide-react v0.453.0 - ISC
228
- *
229
- * This source code is licensed under the ISC license.
230
- * See the LICENSE file in the root directory of this source tree.
231
- */const Fa=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
232
- * @license lucide-react v0.453.0 - ISC
233
- *
234
- * This source code is licensed under the ISC license.
235
- * See the LICENSE file in the root directory of this source tree.
236
- */const Pa=s.createLucideIcon("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
237
- * @license lucide-react v0.453.0 - ISC
238
- *
239
- * This source code is licensed under the ISC license.
240
- * See the LICENSE file in the root directory of this source tree.
241
- */const za=s.createLucideIcon("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
242
- * @license lucide-react v0.453.0 - ISC
243
- *
244
- * This source code is licensed under the ISC license.
245
- * See the LICENSE file in the root directory of this source tree.
246
- */const nt=s.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
247
- * @license lucide-react v0.453.0 - ISC
248
- *
249
- * This source code is licensed under the ISC license.
250
- * See the LICENSE file in the root directory of this source tree.
251
- */const _a=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
252
- * @license lucide-react v0.453.0 - ISC
253
- *
254
- * This source code is licensed under the ISC license.
255
- * See the LICENSE file in the root directory of this source tree.
256
- */const bs=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
257
- * @license lucide-react v0.453.0 - ISC
258
- *
259
- * This source code is licensed under the ISC license.
260
- * See the LICENSE file in the root directory of this source tree.
261
- */const qe=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
262
- * @license lucide-react v0.453.0 - ISC
263
- *
264
- * This source code is licensed under the ISC license.
265
- * See the LICENSE file in the root directory of this source tree.
266
- */const Fe=s.createLucideIcon("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
267
- * @license lucide-react v0.453.0 - ISC
268
- *
269
- * This source code is licensed under the ISC license.
270
- * See the LICENSE file in the root directory of this source tree.
271
- */const Va=s.createLucideIcon("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/**
272
- * @license lucide-react v0.453.0 - ISC
273
- *
274
- * This source code is licensed under the ISC license.
275
- * See the LICENSE file in the root directory of this source tree.
276
- */const Ua=s.createLucideIcon("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
277
- * @license lucide-react v0.453.0 - ISC
278
- *
279
- * This source code is licensed under the ISC license.
280
- * See the LICENSE file in the root directory of this source tree.
281
- */const Ga=s.createLucideIcon("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/**
282
- * @license lucide-react v0.453.0 - ISC
283
- *
284
- * This source code is licensed under the ISC license.
285
- * See the LICENSE file in the root directory of this source tree.
286
- */const rt=s.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"}]]);/**
287
- * @license lucide-react v0.453.0 - ISC
288
- *
289
- * This source code is licensed under the ISC license.
290
- * See the LICENSE file in the root directory of this source tree.
291
- */const Ya=s.createLucideIcon("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
292
- * @license lucide-react v0.453.0 - ISC
293
- *
294
- * This source code is licensed under the ISC license.
295
- * See the LICENSE file in the root directory of this source tree.
296
- */const $a=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
297
- * @license lucide-react v0.453.0 - ISC
298
- *
299
- * This source code is licensed under the ISC license.
300
- * See the LICENSE file in the root directory of this source tree.
301
- */const qa=s.createLucideIcon("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
302
- * @license lucide-react v0.453.0 - ISC
303
- *
304
- * This source code is licensed under the ISC license.
305
- * See the LICENSE file in the root directory of this source tree.
306
- */const lt=s.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"}]]);/**
307
- * @license lucide-react v0.453.0 - ISC
308
- *
309
- * This source code is licensed under the ISC license.
310
- * See the LICENSE file in the root directory of this source tree.
311
- */const Ha=s.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
312
- * @license lucide-react v0.453.0 - ISC
313
- *
314
- * This source code is licensed under the ISC license.
315
- * See the LICENSE file in the root directory of this source tree.
316
- */const Wa=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
317
- * @license lucide-react v0.453.0 - ISC
318
- *
319
- * This source code is licensed under the ISC license.
320
- * See the LICENSE file in the root directory of this source tree.
321
- */const Le=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
322
- * @license lucide-react v0.453.0 - ISC
323
- *
324
- * This source code is licensed under the ISC license.
325
- * See the LICENSE file in the root directory of this source tree.
326
- */const ye=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
327
- * @license lucide-react v0.453.0 - ISC
328
- *
329
- * This source code is licensed under the ISC license.
330
- * See the LICENSE file in the root directory of this source tree.
331
- */const Ka=s.createLucideIcon("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
332
- * @license lucide-react v0.453.0 - ISC
333
- *
334
- * This source code is licensed under the ISC license.
335
- * See the LICENSE file in the root directory of this source tree.
336
- */const ze=s.createLucideIcon("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
337
- * @license lucide-react v0.453.0 - ISC
338
- *
339
- * This source code is licensed under the ISC license.
340
- * See the LICENSE file in the root directory of this source tree.
341
- */const Ja=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Qa(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Oa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>ot(c))}})}})}}function ot(t){return{...t,customCfg:Xa(t.customCfg),data:[]}}function Xa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Za(t,n,a,r){if(!r)return null;const l=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:a,operation:"create"})}async function ys(t,n){if(!n)return null;const{id:a,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function en(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function sn(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,u]=A.useState(!1),[d,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){u(!0);const x=ss(h),b=await Za(t,x,p,g==null?void 0:g.accessToken);b&&(o([...l||[],b]),c(b.id),m(!1)),u(!1)}return e.jsxs(s.Dialog,{open:d,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{n(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function tn(){const[t,n]=A.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function u(m){if(await en(m,c==null?void 0:c.accessToken)){const p=a==null?void 0:a.filter(g=>g.id!==m);l(p||[]),o("original")}}async function d(m){const h=a==null?void 0:a.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});l(h||[]);const p={...m,isDefault:!m.isDefault};await ys(p,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await ys(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),d(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function an({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function u(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function d(){if(!r)return;a(!1),l(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&d()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!r,children:"Download"})]})]})})]})}function it({triggerButtonClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState("create"),[o,c]=A.useState("current"),i=s.useDashboardStore(C=>{var S;return(S=C.dashboard)==null?void 0:S.sheets}),u=s.useDashboardStore(C=>C.selectedSheetId),d=i==null?void 0:i.find(C=>C.id===u),m=i&&i.length>1,{schedules:h,isLoading:p,createSchedule:g,deleteSchedule:j,isSubmitting:x,submitError:b,deletingId:f,refetch:N}=s.useSchedule({reportType:"DASHBOARD",enabled:n}),T=async C=>{try{const S={format:"pdf",sheetSelection:o,pdfOptions:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};o==="current"&&d&&(S.currentSheetId=d.id,S.currentSheetName=d.title),await g({...C,reportParams:S}),l("active")}catch(S){console.error("Failed to create schedule:",S)}},I=async C=>{try{await j(C)}catch(S){console.error("Failed to delete schedule:",S)}};return e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-[520px] p-0",children:e.jsxs(s.Tabs,{value:r,onValueChange:C=>l(C),className:"w-full",children:[e.jsxs("div",{className:"border-b px-6 pb-3 pt-6",children:[e.jsxs("div",{className:"mb-4 space-y-1",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Dashboard"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your dashboard and report schedules"})]}),e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Schedule"]}),e.jsxs(s.TabsTrigger,{value:"active",className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4"}),"Active Schedules",h&&h.length>0&&e.jsx(s.Badge,{variant:"secondary",className:"ml-1 h-5 px-1",children:h.length})]})]})]}),e.jsxs(s.TabsContent,{value:"create",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:[m&&e.jsxs("div",{className:"mb-6 space-y-2",children:[e.jsx(s.Label,{children:"Sheet Selection"}),e.jsxs(s.RadioGroup,{value:o,onValueChange:C=>c(C),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"current",id:"current-sheet"}),e.jsxs(s.Label,{htmlFor:"current-sheet",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.FileText,{className:"mr-2 h-4 w-4"}),"Current sheet (",(d==null?void 0:d.title)||"Sheet",")"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"all",id:"all-sheets"}),e.jsxs(s.Label,{htmlFor:"all-sheets",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.Files,{className:"mr-2 h-4 w-4"}),"All sheets (",i==null?void 0:i.length," sheets)"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o==="current"?"Only the currently selected sheet will be included in the report":"All sheets in the dashboard will be included in the report"})]}),e.jsx(s.ScheduleForm,{reportType:"DASHBOARD",onSubmit:T,isSubmitting:x,submitError:b})]}),e.jsx(s.TabsContent,{value:"active",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:h&&h.length>0?e.jsx(s.ScheduleManager,{schedules:h,onDelete:I,isDeleting:f,isLoading:p,onRefresh:N}):e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.Clock,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),e.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Create Schedule" tab to add your first subscription'})]})})]})})]})}function ct(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function nn({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:u,onDuplicateVisual:d,onShareVisual:m,formatDate:h}){var S,y,E;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),x=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen),[b,f]=A.useState(!1),[N,T]=A.useState(!1);A.useEffect(()=>{a?(f(!0),T(!0)):N&&(f(!1),T(!1))},[a,N]);const I=()=>e.jsx(rs,{className:"h-4 w-4"}),C=()=>{p(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:v=>i==null?void 0:i(t.id,{title:v}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:v=>i==null?void 0:i(t.id,{description:v}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:v=>v.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:b,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Pa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),u(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function ts({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Re({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var u;const c=((u=a.find(d=>d.value===t))==null?void 0:u.label)||t,i=a.filter(d=>d.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(d=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:d.value,disabled:r}),n(d.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.description})]})},d.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function dt({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(u=>u.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:u=>r(o.id,u),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function ut({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function mt({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const u=n.find(d=>d.id===i);return(u==null?void 0:u.name)||"Unknown User"},c=i=>{const u=l.find(d=>d.value===i);return(u==null?void 0:u.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function ht(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ve(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function rn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function xt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ln(t,n,a){const r=xt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function on({user:t}){return xt(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function cn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=rn((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),u=a.find(h=>h.id===t.id),d=u?u.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Re,{currentRole:d,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ve(d,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function dn({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Fe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function un({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function mn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],u=c.specificTenantUsers||[],d=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((p,g)=>{var f,N;const j=((f=n.find(T=>T.id===p.orgUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(T=>T.id===p.orgUserId))==null?void 0:N.type)||"",b=ve(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",u.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[u.slice(0,3).map((p,g)=>{var f,N;const j=((f=n.find(T=>T.id===p.tenantUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(T=>T.id===p.tenantUserId))==null?void 0:N.type)||"",b=ve(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)}),u.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",u.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:d.map((p,g)=>{const j=ve(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((p,g)=>{const j=ve(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,g)=>{const j=ve(p.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),!i.length&&!u.length&&!d.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((u,d)=>{var g,j;const m=((g=n.find(x=>x.id===u.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(x=>x.id===u.tenantUserId))==null?void 0:j.type)||"",p=ve(u.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},d)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((u,d)=>{const m=ve(u.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,u)=>{var p,g;const d=((p=n.find(j=>j.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",m=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=ve(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:d}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,u)=>{const d=ve(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:d})]},u)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function hn({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function xn({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:u,usersToUpdate:d,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:p,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(u==null?void 0:u.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(on,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Re,{currentRole:n==null?void 0:n.role,onRoleChange:j=>p(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(cn,{user:t,userShare:n,usersToUpdate:d,currentUser:u,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(dn,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(un,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function pt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:u,handleUpdateAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(C=>{const S=m.some(E=>E.id===C),y=h.includes(C);S?j.removeSelectedUser(C):y?j.removeUserFromRemove(C):j.addSelectedUser({id:C,role:"VIEWER"})}),b=i||j.updateSelectedUserRole,f=u||j.addUserToRemove,N=d||((C,S,y)=>{j.addUserToUpdate({id:C,currentRole:S,newRole:y})}),T=l,I=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(mn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?j.setSelectedUsers([]):j.setSelectedUsers(T.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(hn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(C=>{const S=t?ln(C,t,o):void 0,y=I.includes(C.id),E=!!S,v=E&&!y,O=m.some(w=>w.id===C.id),k=m.find(w=>w.id===C.id),F=r(C.type);return e.jsx(xn,{user:C,userShare:S,isUserRemoving:y,hasAccess:v,hasAccessFromAPI:E,isSelected:O,selectedUser:k,roleOptions:F,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:b},C.id)})]})]})}function ws({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(ze,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function pn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const u=s.useShareCurrentMode(),d=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,p=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,j=o,x=m==="NONE"||!m,b=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Va,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":j||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",u==="allOrgUsers"?"Organization":u==="allTenantUsers"?"Tenant":u==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:d.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function ft({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:u}){const d=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:d(n.role)}:{role:"NONE"},p=i?{currentRole:d(i.currentRole),newRole:d(i.newRole)}:null,g=(x,b)=>{o(x,b)},j=()=>{c()};return e.jsx(pn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:u})}const fn=async(t,n={})=>{const a={};return n.search&&(a.search=n.search),n.type&&(a.type=n.type),n.active!==void 0&&(a.active=n.active.toString()),n.tenantId&&(a.tenantId=n.tenantId),n.limit&&(a.limit=n.limit.toString()),n.offset&&(a.offset=n.offset.toString()),n.page&&(a.page=n.page.toString()),n.pageSize&&(a.pageSize=n.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,a)};function gn(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>fn((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(u,d)=>d instanceof Error&&d.message.includes("401")||d instanceof Error&&d.message.includes("403")?!1:u<2,retryDelay:u=>Math.min(1e3*2**u,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function _e(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:u,isError:d}=gn(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:u,isErrorLoadingUsers:d,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function jn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Z,se;const i=s.useShareSelectedTab(),u=s.useShareSelectedTenant(),{searchQuery:d,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),b=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,T]=A.useState("specific_users"),I=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&u)return u},{allUsers:S,existingShares:y,isLoadingUsers:E}=_e({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:I(),tenantId:C()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const v=W=>{var G,Q;const J=W;if(T(J),r==null||r(J),f.setCurrentContext("org-tab"),J==="specific_users")f.setCurrentMode("specificOrgUsers");else if(J==="all_users"){f.setCurrentMode("allOrgUsers");const P=(Q=(G=y==null?void 0:y.shares)==null?void 0:G.orgUsersOnly)==null?void 0:Q[0];P&&P.role!==void 0&&f.setOrgWideRole(P.role)}},O=S.filter(W=>W.name.toLowerCase().includes(d.toLowerCase())||W.email.toLowerCase().includes(d.toLowerCase())),k=S.filter(W=>p.some(J=>J.id===W.id)),F=W=>{var P,U;const J=p.some(te=>te.id===W),G=g.includes(W),Q=(U=(P=y==null?void 0:y.shares)==null?void 0:P.specificOrgUsers)==null?void 0:U.some(te=>te.orgUserId===W);J?f.removeSelectedUser(W):G?f.removeUserFromRemove(W):Q||f.addSelectedUser({id:W,role:"VIEWER"})},w=(W,J)=>{f.updateSelectedUserRole(W,J)},D=W=>{f.addUserToRemove(W),f.removeSelectedUser(W)},M=W=>{f.removeUserFromRemove(W)},R=W=>{f.removeUserFromUpdate(W)},L=(W,J)=>{f.setOrgWideRole(J)},B=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(se=(Z=y==null?void 0:y.shares)==null?void 0:Z.orgUsersOnly)==null?void 0:se[0];A.useEffect(()=>{N==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[N,z,f]);const $=E,_=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:N,onShareTypeChange:v,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(ze,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:d,onChange:m}),e.jsx(dt,{selectedUsers:p,selectedUserObjects:k,onRemove:F,onRoleChange:w,getRoleOptions:be}),e.jsx(ut,{usersToRemove:g,allUsers:O,onRemove:M}),e.jsx(mt,{usersToUpdate:j,allUsers:O,onRemove:R,getRoleOptions:be}),e.jsx(pt,{existingShares:y,isInitialLoading:$,isSearching:_,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:F,handleUserRoleChange:w,handleRemoveAccess:D,handleUpdateAccess:(W,J,G)=>{f.addUserToUpdate({id:W,currentRole:J,newRole:G})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ft,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:L,onRemoveAccess:B,allUsersToUpdate:x==="allOrgUsers"&&b!==((z==null?void 0:z.role)||"NONE")?{currentRole:(z==null?void 0:z.role)||"NONE",newRole:b}:null,allUsersToRemove:x==="allOrgUsers"&&(z==null?void 0:z.role)===void 0})})]}):null}function bn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function yn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function gt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:u,handleUpdateAccess:d}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),j=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(x=>{const b=n==null?void 0:n.find(y=>y.groupId===x.id),f=m.some(y=>y.id===x.id),N=h.includes(x.id),T=p.find(y=>y.id===x.id),I=!!b&&!N;let S=(b==null?void 0:b.role)||"VIEWER";if(f){const y=m.find(E=>E.id===x.id);S=(y==null?void 0:y.role)||"VIEWER"}else T&&(S=T.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",I&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${x.id}`,checked:I?!N:f,disabled:!1,onCheckedChange:()=>{I?N?g.removeGroupFromRemove(x.id):u==null||u(x.id):c==null||c(x.id)}}),e.jsxs("label",{htmlFor:`group-${x.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:x.name}),x.type==="ORG_GROUP"?e.jsx(Ss,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",yn(x.type)),children:bn(x.type)}),x.type==="TENANT_GROUP"&&x.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",x.tenantName]})]}),x.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[I&&!N?e.jsx(Re,{currentRole:S,onRoleChange:y=>{b&&y!==b.role&&(d==null||d(x.id,b.role,y))},roleOptions:j,disabled:!1,allowDropdown:!0,className:T?"border-orange-300 bg-orange-100":""}):f&&!I&&e.jsx(Re,{currentRole:S,onRoleChange:y=>i==null?void 0:i(x.id,y),roleOptions:j,disabled:!1}),I&&!N&&!T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>u==null?void 0:u(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(x.id),children:"Undo"}),T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(x.id),children:"Cancel"})]})]},x.id)})})]})}function jt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(u=>u.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(Ss,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{currentRole:c.role,onRoleChange:u=>r(c.id,u),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}const vn=async(t,n={})=>{const a={};n.search&&(a.search=n.search),n.type&&n.type!=="all"&&(a.type=n.type),n.tenantId&&(a.tenantId=n.tenantId),n.organizationId&&(a.organizationId=n.organizationId),n.includeMembers!==void 0&&(a.includeMembers=n.includeMembers.toString()),n.page&&(a.page=n.page.toString()),n.limit&&(a.limit=n.limit.toString());const r="https://semaphor.cloud/api/management/v1/groups";console.log("Fetching groups with params:",{endpoint:r,queryParams:a});const l=await s.getRequest(r,t,a);return console.log("Groups API response:",l),l};function Nn(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["groups",t],queryFn:()=>vn((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(u,d)=>d instanceof Error&&d.message.includes("401")||d instanceof Error&&d.message.includes("403")?!1:u<2,retryDelay:u=>Math.min(1e3*2**u,3e4),staleTime:6e4});return{groups:((o=l.data)==null?void 0:o.groups)||[],total:((c=l.data)==null?void 0:c.total)||0,hasMore:((i=l.data)==null?void 0:i.hasMore)||!1,isLoading:l.isLoading,isError:l.isError,error:l.error,isFetching:l.isFetching,refetch:l.refetch}}function bt(t,n){const{tokenProps:a}=s.useSemaphorContext(),r={limit:100};return t==="organization"||a!=null&&a.orgUserId?r.type="all":(t==="tenant"||a!=null&&a.endUserId)&&(r.type="TENANT_GROUP",(n||a!=null&&a.tenantId)&&(r.tenantId=n||a.tenantId)),Nn(r)}function Ys({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var X;const{searchQuery:i,debouncedSearchQuery:u,setSearchQuery:d}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),j=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),b=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),T=s.useShareSelectedTenant(),I=s.useShareManagementActions(),{data:C,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:y,isLoading:E}=bt("tenant",(a==null?void 0:a.tenantId)||T),[v,O]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),I.setCurrentMode("specificTenantUsers")):(I.setCurrentContext("tenant-tab"),I.setCurrentMode("allTenants"))},[I,a==null?void 0:a.type]);const k=V=>{var ee,ne,re,je;O(V);let H;if(V==="specific_tenant_users"?H="specific_users":V==="all_tenant_users"||V==="all_tenants"?H="all_users":V==="groups"?H="groups":H="specific_users",r==null||r(H),V==="groups"?(I.setCurrentContext("group-share"),I.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(I.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&I.setSelectedTenant(a.tenantId))):(I.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?I.setCurrentMode("allTenantUsers"):V==="all_tenants"&&I.setCurrentMode("allTenants")),V==="all_tenant_users"){const me=(ne=(ee=D==null?void 0:D.shares)==null?void 0:ee.tenantWide)==null?void 0:ne[0];me&&me.role!==void 0&&I.setTenantWideRole(me.role)}else if(V==="all_tenants"){const me=(je=(re=D==null?void 0:D.shares)==null?void 0:re.allTenantsOnly)==null?void 0:je[0];me&&me.role!==void 0&&I.setAllTenantsRole(me.role)}},F=V=>{I.setSelectedTenant(V)},{allUsers:w,existingShares:D,isLoadingUsers:M,isErrorLoadingUsers:R,isLoadingShares:L,isErrorLoadingShares:B}=_e({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:T}),z=V=>{var re,je;const H=m.some(me=>me.id===V),ee=h.includes(V),ne=(je=(re=D==null?void 0:D.shares)==null?void 0:re.specificTenantUsers)==null?void 0:je.some(me=>me.tenantUserId===V);H?I.removeSelectedUser(V):ee?I.removeUserFromRemove(V):ne||I.addSelectedUser({id:V,role:"VIEWER"})},$=(V,H)=>{I.updateSelectedUserRole(V,H)},_=V=>{I.addUserToRemove(V),I.removeSelectedUser(V)},Z=V=>{I.removeUserFromRemove(V)},se=V=>{I.removeUserFromUpdate(V)},W=(V,H,ee)=>{I.addUserToUpdate({id:V,currentRole:H,newRole:ee})},J=(V,H)=>{v==="all_tenant_users"?I.setTenantWideRole(H):v==="all_tenants"&&I.setAllTenantsRole(H)},G=()=>{v==="all_tenant_users"?I.setTenantWideRole("VIEWER"):v==="all_tenants"&&I.setAllTenantsRole("VIEWER")},P=(()=>{var V,H,ee,ne;return b==="allTenants"?(H=(V=D==null?void 0:D.shares)==null?void 0:V.allTenantsOnly)==null?void 0:H[0]:b==="allTenantUsers"?(ne=(ee=D==null?void 0:D.shares)==null?void 0:ee.tenantWide)==null?void 0:ne[0]:null})();A.useEffect(()=>{var V,H,ee,ne;if(v==="all_tenant_users"){const re=(H=(V=D==null?void 0:D.shares)==null?void 0:V.tenantWide)==null?void 0:H[0];re&&re.role!==void 0&&I.setTenantWideRole(re.role)}else if(v==="all_tenants"){const re=(ne=(ee=D==null?void 0:D.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:ne[0];re&&re.role!==void 0&&I.setAllTenantsRole(re.role)}},[v,D,I]);const U=w.filter(V=>m.some(H=>H.id===V.id)),te=V=>{const H=g.some(re=>re.id===V),ee=j.includes(V),ne=ie==null?void 0:ie.some(re=>re.groupId===V);H?I.removeSelectedGroup(V):ee?I.removeGroupFromRemove(V):ne||I.addSelectedGroup({id:V,role:"VIEWER"})},le=(V,H)=>{I.updateSelectedGroupRole(V,H)},Y=V=>{I.addGroupToRemove(V),I.removeSelectedGroup(V)},q=(V,H,ee)=>{I.addGroupToUpdate({id:V,currentRole:H,newRole:ee})},ae=y.filter(V=>g.some(H=>H.id===V.id)),oe=A.useMemo(()=>v!=="groups"?[]:y.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(i.toLowerCase())||V.description&&V.description.toLowerCase().includes(i.toLowerCase())),[y,v,i]),ie=A.useMemo(()=>{var H,ee;const V=((H=D==null?void 0:D.shares)==null?void 0:H.specificGroups)||((ee=D==null?void 0:D.shares)==null?void 0:ee.groups)||[];return!V||V.length===0?[]:V.filter(ne=>{const re=y.find(je=>je.id===ne.groupId);return(re==null?void 0:re.type)==="TENANT_GROUP"})},[D,y]),ue=M||L||v==="groups"&&E,xe=R||B,pe=()=>(a==null?void 0:a.type)==="tenant"||v==="all_tenants"||v==="groups"?!0:T&&(v==="specific_tenant_users"||v==="all_tenant_users");return e.jsxs(e.Fragment,{children:[xe&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!xe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ws,{shareType:v,onShareTypeChange:k,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(ze,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Vs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(ze,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:T||"",onValueChange:F,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(X=C==null?void 0:C.tenants)==null?void 0:X.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),pe()?e.jsx(e.Fragment,{children:v==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:d}),e.jsx(dt,{selectedUsers:m,selectedUserObjects:U,onRemove:V=>z(V),onRoleChange:$,getRoleOptions:be}),e.jsx(ut,{usersToRemove:h,allUsers:w,onRemove:Z}),e.jsx(mt,{usersToUpdate:p,allUsers:w,onRemove:se,getRoleOptions:be}),e.jsx(pt,{existingShares:D,isInitialLoading:!!ue,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:w,currentUser:a,handleUserToggle:z,handleUserRoleChange:$,handleRemoveAccess:_,handleUpdateAccess:W})]}):v==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(jt,{selectedGroups:g,groupObjects:ae,onRemove:te,onRoleChange:le,getRoleOptions:be}),j.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",j.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(gt,{groups:oe,existingGroupShares:ie,isLoading:E,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:te,handleGroupRoleChange:le,handleRemoveAccess:Y,handleUpdateAccess:q})]}):v==="all_tenant_users"||v==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ft,{currentUser:a,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:J,onRemoveAccess:G,allUsersToUpdate:b==="allTenantUsers"&&((P==null?void 0:P.role)===void 0||f!==P.role)||b==="allTenants"&&((P==null?void 0:P.role)===void 0||N!==P.role)?{currentRole:(P==null?void 0:P.role)||"VIEWER",newRole:b==="allTenantUsers"?f:N}:null,allUsersToRemove:b==="allTenantUsers"&&(P==null?void 0:P.role)===void 0||b==="allTenants"&&(P==null?void 0:P.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Vs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function Cn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var k,F;const{searchQuery:i,setSearchQuery:u}=s.useShareSearchWithDebounce(),d=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),[g,j]=A.useState("org_groups"),x=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:b,isLoading:f}=bt(x(),a==null?void 0:a.tenantId),{existingShares:N}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),T=b.filter(w=>g==="org_groups"&&w.type!=="ORG_GROUP"||g==="tenant_groups"&&w.type!=="TENANT_GROUP"?!1:w.name.toLowerCase().includes(i.toLowerCase())||w.description&&w.description.toLowerCase().includes(i.toLowerCase())),I=((k=N==null?void 0:N.shares)==null?void 0:k.specificGroups)||((F=N==null?void 0:N.shares)==null?void 0:F.groups)||[];A.useEffect(()=>{p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},[p]);const C=w=>{const D=w;j(D),r==null||r(D==="org_groups"?"specific_groups":"all_groups"),p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},S=b.filter(w=>d.some(D=>D.id===w.id)),y=w=>{const D=d.some(L=>L.id===w),M=m.includes(w),R=I==null?void 0:I.some(L=>L.groupId===w);D?p.removeSelectedGroup(w):M?p.removeGroupFromRemove(w):R||p.addSelectedGroup({id:w,role:"VIEWER"})},E=(w,D)=>{p.updateSelectedGroupRole(w,D)},v=w=>{p.addGroupToRemove(w),p.removeSelectedGroup(w)},O=(w,D,M)=>{p.addGroupToUpdate({id:w,currentRole:D,newRole:M})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:g,onShareTypeChange:C,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(Ss,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(jt,{selectedGroups:d,groupObjects:S,onRemove:y,onRoleChange:E,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(gt,{groups:T,existingGroupShares:I,isLoading:f,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:y,handleGroupRoleChange:E,handleRemoveAccess:v,handleUpdateAccess:O})]})]}):null}const yt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),u=s.useShareSelectedTenant(),d=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),p=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:u,orgWideRole:d,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,u,d,m,h,p]),j=A.useMemo(()=>b=>s.validateShareData(b),[]),x=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!u)return!1}else if(n==="specificTenantUsers")return u?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,u]);return{buildShareData:g,validateShareData:j,isCurrentStateValid:x,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:u,orgWideRole:d,allTenantsRole:m,tenantWideRole:h}};function $s({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:u,onRemoveAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),b=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:T}=yt(),I=a||r||l,C=()=>{var O,k,F,w;if(I)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}else if(i==="all_users"){if(!u||u.role===void 0)return"Share with All Users";const D=u.role;return j===D?"Remove Access":"Update Access"}else if(i==="all_tenants"){const D=(k=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:k[0];if(!D||D.role===void 0)return"Share with All Tenants";const M=D.role;return x===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const D=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"Share with All Tenant Users";const M=D.role;return b===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}return"Share"},S=()=>I||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,y=()=>{const O=f();O&&N(O)&&o(O)},E=()=>{var O,k,F,w;if(i==="all_users")if(!u||u.role===void 0){const D=f();D&&N(D)&&o(D)}else{const D=u.role;if(j===D)d==null||d();else{const R=f();if(R&&N(R)){const L={...R,updateAccess:!0};o(L)}}}else if(i==="all_tenants"){const D=(k=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:k[0];if(!D||D.role===void 0){const M=f();M&&N(M)&&o(M)}else{const M=D.role;if(x===M)d==null||d();else{const L=f();if(L&&N(L)){const B={...L,updateAccess:!0};o(B)}}}}else if(i==="all_tenant_users"){const D=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0){const M=f();M&&N(M)&&o(M)}else{const M=D.role;if(b===M)d==null||d();else{const L=f();if(L&&N(L)){const B={...L,updateAccess:!0};o(B)}}}}},v=()=>{var O,k,F,w;if(i==="all_users"){if(!u||u.role===void 0)return"default";const D=u.role;return j===D?"destructive":"default"}else if(i==="all_tenants"){const D=(k=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:k[0];if(!D||D.role===void 0)return"default";const M=D.role;return x===M?"destructive":"default"}else if(i==="all_tenant_users"){const D=(w=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"default";const M=D.role;return b===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:I,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||I,variant:"default",children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),!I&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:E,disabled:S(),variant:v(),children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!I&&C()]})]})}function Sn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const u=s.useShareSelectedUsers(),d=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),p=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const j=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:x,validateShareData:b,isCurrentStateValid:f}=yt(),N=n||a||r,T=()=>{if(N)return"Updating...";if(c==="specific_users"){if(u.length===0&&d.length===0&&m.length===0)return"Select users to share with";const v=u.length+d.length+m.length;return v===0?"Select users to share with":u.length>0&&d.length>0?`Update access for ${v} user${v!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Remove access for ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:m.length>0&&u.length===0&&d.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&p.length===0&&g.length===0)return"Select groups to share with";const v=h.length+p.length+g.length;return v===0?"Select groups to share with":h.length>0&&p.length>0?`Update access for ${v} group${v!==1?"s":""}`:p.length>0&&h.length===0&&g.length===0?`Remove access for ${p.length} group${p.length!==1?"s":""}`:h.length>0&&p.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&p.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${v} group${v!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const v=i.role;return j===v?"Remove Access":"Update Access"}return"Share"},I=()=>N||!t?!0:!f,C=()=>{const v=x();v&&b(v)&&l(v)},S=()=>{const v=x();v&&b(v)&&l(v)},y=()=>{if(!i||i.role==="NONE"){const v=x();v&&b(v)&&l(v)}else{const v=i.role;if(j===v){const k=x();if(k&&b(k)){const F={...k,removeAccess:!0};l(F)}}else{const k=x();if(k&&b(k)){const F={...k,updateAccess:!0};l(F)}}}},E=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(u.length>0||d.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||p.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:y,disabled:I(),variant:E(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),!N&&T()]})]})}function wn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:u,onRemoveAccess:d}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:p})},j=()=>m.length>0||h.length>0||p.length>0,x=()=>h.length>0&&m.length===0&&p.length===0?"Remove Access":p.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",b=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),p.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",p.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:b,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!j()||b,children:[b&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),x()]})]})]})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Dn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:u}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const p=ge(r,l,d.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{u()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:b.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{u()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="allTenantUsers"){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:p}=t;if(m&&m.length>0){const g=Se(r,l,m.map(j=>{var b,f;const x=(f=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{u()}})}if(h&&h.length>0&&h.forEach(g=>{const j=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.newRole}]);o(j,{onSuccess:()=>{u()}})}),d&&d.length>0){const g=ge(r,l,d.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));o(g,{onSuccess:()=>{u()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(d,{onSuccess:()=>{u()}})}else if(t.updateAccess){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else{const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const p=ge(r,l,d.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(p,{onSuccess:()=>{u()}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:b.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{u()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:d,groupsToRemove:m,groupsToUpdate:h}=t;if(d&&d.length>0){const p=ge(r,l,d.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(p,{onSuccess:()=>{var g;u(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${d.length} group${d.length!==1?"s":""}`)}})}if(m&&m.length>0){const p=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(p,{onSuccess:()=>{var g;u(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(p=>{const g=ge(r,l,[{scope:"group",groupId:p.id,role:p.newRole}]);o(g,{onSuccess:()=>{var j;u(),(j=n.resetGroupSelections)==null||j.call(n),s.ue.success("Updated access for group")}})})}break}}function kn(t,n,a,r){var d,m,h,p,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:u}=r;if(o)if(t.length>0){const x=Se(l,o,t.map(b=>{var N,T;const f=(T=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:T.find(I=>I.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(f==null?void 0:f.role)||"VIEWER"}}));c(x,{onSuccess:()=>{u()},onError:b=>{console.error("Remove access failed:",b)}})}else{const x=n==="tenant"&&a==="allTenants",b=n==="tenant"&&a==="allTenantUsers";if(x){const f=(m=(d=i==null?void 0:i.shares)==null?void 0:d.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(b){const f=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(f){const N=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const f=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(f){const N=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function Tn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:u}=_e({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const j={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:u,resetUserSelections:d,resetGroupSelections:m};Dn(g,j,i)},[t,n,a,u,d,m,i]),p=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:u,resetUserSelections:d};kn(l,o||"",c||"",g)},[t,n,a,u,d,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:p}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var w,D,M,R,L,B,z,$;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[u,d]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),j=s.useShareCurrentMode(),x=s.useShareResource(),b=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=Tn(t.id,(_,Z)=>{x.mutate(_,{...Z,onSuccess:()=>{var se;(se=Z==null?void 0:Z.onSuccess)==null||se.call(Z),r==null||r()}})},(_,Z)=>{b.mutate(_,{...Z,onSuccess:()=>{var se;(se=Z==null?void 0:Z.onSuccess)==null||se.call(Z),l==null||l()}})}),T=x.isPending,I=b.isPending,C=x.isPending,{existingShares:S}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:y}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),E=(D=(w=S==null?void 0:S.shares)==null?void 0:w.tenantWide)==null?void 0:D[0],v=(R=(M=y==null?void 0:y.shares)==null?void 0:M.orgUsersOnly)==null?void 0:R[0],O=()=>{if(g==="org")return u;switch(j){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},k=A.useCallback(()=>{p.resetShareState(),a()},[p,a]),F=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:k,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),F?e.jsxs(s.Tabs,{value:g,onValueChange:_=>{const Z=_;p.setSelectedTab(Z),p.resetUserSelections(),p.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(jn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:d,isSharing:T,isUpdating:C,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Ys,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:T,isUpdating:C,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Cn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:T,isUpdating:C,isRemoving:I})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Ys,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:_=>i(_),isSharing:T,isUpdating:C,isRemoving:I})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?g==="org"?e.jsx($s,{resource:t,existingShares:y,isSharing:T,isRemoving:I,isUpdating:C,onShare:f,onClose:a,shareTabType:u,currentAllUsersShare:v,onRemoveAccess:N}):g==="tenant"?e.jsx($s,{resource:t,existingShares:S,isSharing:T,isRemoving:I,isUpdating:C,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:E,onRemoveAccess:N}):e.jsx(wn,{resource:t,existingShares:y,isSharing:T,isRemoving:I,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(B=(L=y==null?void 0:y.shares)==null?void 0:L.allOrgGroups)==null?void 0:B[0]:($=(z=S==null?void 0:S.shares)==null?void 0:z.allTenantGroups)==null?void 0:$[0],onRemoveAccess:N}):e.jsx(Sn,{resource:t,isSharing:T,isRemoving:I,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:E,onRemoveAccess:N})})]})})}function En(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ds(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const u=await import(i);if(typeof u.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>u.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function In(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function qs(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],l=a.getQueryData(r);if(l)return console.log("Using cached visual data for:",n),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",n);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function An(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function Mn(){var p;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((p=a.customCardPreferences)==null?void 0:p.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),u=s.useEditorStore(g=>g.selectedConnectionId),d=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=En(m),t(g));const j=(f=r==null?void 0:r.getState())==null?void 0:f.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:u,sql:g,customCfg:d?a.customCfg:null,preferences:a.preferences,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},b=n.cards.map(N=>N.id===a.id?x:N);return{...n,cards:b,activeCardId:In(b,n.activeCardId)}},[a,n,d,l,o,c,i,u,t,r,m])}}function ks(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:u,addFrame:d,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=s.useVisualById((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async x=>{try{r(x);const{data:b,fromCache:f}=await qs((t==null?void 0:t.accessToken)||"",x.id,n);return An(b,l,o,c,i),{success:!0,fromCache:f}}catch(b){return console.error("Error editing visual:",b),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,l,o,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:b,fromCache:f}=await qs((t==null?void 0:t.accessToken)||"",x.id,n),N=b.frameObject;if(!N)return{success:!1,error:"Visual has no frame data"};const T={...N,id:s.v4()};return d(h,T,"end"),c(!0),u(T.id),m(!1),{success:!0,fromCache:f}}catch(b){return console.error("Error adding visual:",b),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,d,c,u,m]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:Mn().getUpdatedFrame,refetch:p.refetch}}function Ln(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(!1),[m,h]=A.useState(null),[p,g]=A.useState(!1),[j,x]=A.useState(null),[b,f]=A.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:I,handleAddLibraryVisual:C}=ks(),{resources:S,isLoading:y,isError:E,createResource:v,updateResource:O,deleteResource:k,duplicateResource:F,isCreating:w,isDeleting:D}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const M=S.filter(U=>{var te,le;return((te=U==null?void 0:U.title)==null?void 0:te.toLowerCase().includes(t.toLowerCase()))||((le=U==null?void 0:U.description)==null?void 0:le.toLowerCase().includes(t.toLowerCase()))}),R=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),L=()=>{l.trim()&&v({title:l,description:c,isPrivate:!1})},B=U=>{x(U),g(!0)},z=()=>{j&&k(j.id)},{startUpdating:$,stopUpdating:_,isUpdating:Z}=s.useResourceUpdateState(),se=(U,te)=>{const le=te.title!==void 0?"title":"description";$(U,le),O({resourceId:U,data:te},{onSuccess:()=>{_(U,le)},onError:()=>{_(U,le)}})},W=U=>{f(U),F(U,{onSettled:()=>f(null)})},J=U=>{I(U)},G=U=>{C(U)},Q=U=>{const te=S.find(le=>le.id===U);te&&O({resourceId:U,data:{isPrivate:!te.isPrivate}})},P=U=>{h(U),d(!0)};return y?e.jsx(ct,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:U=>o(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:U=>i(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:L,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||w,children:w?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:w,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:w,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),w?"Creating...":"Create New Visual"]})}),S&&S.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>n(U.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:M.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):M.map(U=>e.jsx(nn,{visual:U,onAddVisual:G,onEditVisual:J,onUpdateVisual:se,onDeleteClick:B,onDuplicateVisual:W,onTogglePrivacy:Q,onShareVisual:P,isDeleting:D,isDuplicating:b===U.id,isTitleUpdating:Z(U.id,"title"),isDescriptionUpdating:Z(U.id,"description"),formatDate:R},U.id))})}),u&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{d(!1),h(null)}}),e.jsx(s.AlertDialog,{open:p,onOpenChange:U=>{!U&&D||(g(U),U||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:D,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,children:D?"Deleting...":"Delete"})]})]})})]})}function Rn({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:u,onShareDashboard:d,formatDate:m,onDashboardItemClick:h}){var S,y,E;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[x,b]=A.useState(!1),[f,N]=A.useState(!1),T=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen);A.useEffect(()=>{a?(b(!0),N(!0)):f&&(b(!1),N(!1))},[a,f]);const I=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),C=()=>{p(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:v=>c==null?void 0:c(t.id,{title:v}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:v=>c==null?void 0:c(t.id,{description:v}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:v=>v.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:b,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function On({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Bn(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,u]=A.useState(""),[d,m]=A.useState(!1),[h,p]=A.useState(null),[g,j]=A.useState(!1),[x,b]=A.useState(null),[f,N]=A.useState(null),T=s.useManagementStore(q=>q.lastSelectedDashboard),I=s.useManagementStore(q=>q.selectedDashboard),C=s.useManagementStore(q=>q.actions.selectDashboard),S=s.useManagementStore(q=>q.actions.clearSelectedDashboard),{tokenProps:y,id:E}=s.useSemaphorContext(),{permissions:v}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:k,isError:F,createResource:w,updateResource:D,deleteResource:M,duplicateResource:R,isCreating:L,isDeleting:B}=s.useDashboardManagement(()=>{j(!1);const q=x==null?void 0:x.id;b(null),(I==null?void 0:I.id)===q&&(!(y!=null&&y.dashboard_id)&&!E?S():T&&T.id!==q&&C(T))},()=>{l(!1),c(""),u("")}),{currentUser:z}=s.useCurrentUserInfo(),$=O.filter(q=>{var ae,oe;return((ae=q==null?void 0:q.title)==null?void 0:ae.toLowerCase().includes(n.toLowerCase()))||((oe=q==null?void 0:q.description)==null?void 0:oe.toLowerCase().includes(n.toLowerCase()))}),_=q=>new Date(q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Z=()=>{o.trim()&&w({title:o,description:i,isPrivate:!1})},se=q=>{var ae;(ae=t.onLoadDashboard)==null||ae.call(t,q)},W=q=>{b(q),j(!0)},J=()=>{x&&M(x.id)},G=q=>{N(q),R(q,{onSettled:()=>N(null)})},{startUpdating:Q,stopUpdating:P,isUpdating:U}=s.useResourceUpdateState(),te=(q,ae)=>{const oe=ae.title!==void 0?"title":"description";Q(q,oe),D({resourceId:q,data:ae},{onSuccess:()=>{P(q,oe)},onError:()=>{P(q,oe)}})},le=q=>{const ae=O.find(oe=>oe.id===q);ae&&D({resourceId:q,data:{isPrivate:!ae.isPrivate}})},Y=q=>{p(q),z==null||z.type,m(!0)};return k?e.jsx(ct,{}):F?e.jsx(On,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[v.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:q=>c(q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:q=>u(q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:Z,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||L,children:L?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),u("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:L,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:L,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),L?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:q=>a(q.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:$.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":v.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),v.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):$.map(q=>e.jsx(Rn,{dashboard:q,isDeleting:B,isDuplicating:f===q.id,isTitleUpdating:U(q.id,"title"),isDescriptionUpdating:U(q.id,"description"),onLoadDashboard:se,onEditDashboard:t.onEditDashboard,onUpdateDashboard:te,onDeleteClick:W,onDuplicateDashboard:G,onTogglePrivacy:le,onShareDashboard:Y,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},q.id))})}),d&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),p(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:q=>{!q&&B||(j(q),q||b(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:B,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:q=>{q.preventDefault(),q.stopPropagation(),J()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:B,children:B?"Deleting...":"Delete"})]})]})})]})}function vt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(b=>b.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(b=>b.actions),{currentUser:c}=s.useCurrentUserInfo(),i=c,{permissions:u}=s.useRoleAwareDisplayPreferences(),d=(u.canAccessVisuals,"dashboards"),[m,h]=s.useLocalStorageState("resource-management-active-tab",d),p=u.canAccessVisuals?m:"dashboards",g=ht(n,{enabled:t}),j=b=>{},x=b=>{console.log("Editing dashboard:",b)};return e.jsx(s.TooltipProvider,{children:e.jsxs("div",{ref:g,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsx("div",{className:"flex items-center gap-2",children:i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"text-xs cursor-help",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"h-3 w-3 mr-1"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"h-3 w-3 mr-1"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role: ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:p,onValueChange:u.canAccessVisuals?h:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pt-4 pb-0",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 mt-4",children:e.jsx(Bn,{onLoadDashboard:j,onEditDashboard:x,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(Ln,{})})]})})]})})}function Fn(){var ue,xe,pe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore(X=>X.theme);const c=s.useDashboardStore(X=>X.lenses),i=s.useDashboardStore(X=>X.selectedLensId),u=c==null?void 0:c.find(X=>X.id===i),d=s.useDashboardStore(X=>X.dashboard);s.useDashboardStore(X=>X.selectedSheetId);const m=s.useDashboardStore(X=>X.isDashboardEditing),h=s.useEditorStore(X=>X.card),p=s.useEditorStore(X=>X.selectedConnectionId),[g,j]=A.useState(!1),[x,b]=A.useState(!1),f=s.useDashboardStore(X=>X.isDashboardPanelOpen),N=s.useDashboardStore(X=>X.actions.setIsDashboardPanelOpen),T=s.useDashboardStore(X=>X.filterValues),I=s.useDashboardStore(X=>X.isVisualEditing),C=s.useManagementStore(X=>X.selectedDashboard),S=s.useManagementStore(X=>X.initialDashboard),y=C?(xe=C==null?void 0:C.permissions)==null?void 0:xe.canEdit:(ue=S==null?void 0:S.permissions)==null?void 0:ue.canEdit,E=s.useDashboardStore(X=>X.showFilters),v=s.useDashboardStore(X=>X.showDashboardJSON),O=s.useDashboardStore(X=>X.onSaveFunction),k=s.useDashboardStore(X=>X.actions.setShowFilters),{addFrame:F,setSelectedFrameId:w}=s.useDashboardStore(X=>X.actions),{getSelectedSheet:D,setIsDashboardEditing:M,setShowDashboardJSON:R}=s.useDashboardStore(X=>X.actions),L=D(),{setInitialDashboard:B,clearSelectedDashboard:z}=s.useManagementStore(X=>X.actions),{resources:$}=s.useResourceManagement(s.ResourceType.DASHBOARD),_=C||S,Z=_?{id:_.id,title:(d==null?void 0:d.title)||_.title||"Dashboard"}:null;A.useEffect(()=>{if($&&$.length>0){const X=d==null?void 0:d.id;if(X){const V=$.find(H=>H.id===X);V&&B(V)}}},[$,d==null?void 0:d.id,B]);const se=n.orgUserId||n.tenantId,W=m&&!I&&se&&y;function J(){var ee,ne;const X=h.dataSource;if(X)return X;const V=(ne=(ee=d.aiContext)==null?void 0:ee.selectedEntities)==null?void 0:ne[0],H=V==null?void 0:V.type;if(V)return{connectionId:V.connectionId,connectionType:V.connectionType,type:H,selectedEntities:[V]}}const G=()=>{if(!m||!L)return;const V={dataSource:J(),mode:"explorer",connectionId:p,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},H={id:s.v4(),cards:[V],activeCardId:V.id};F(L.id,H),w(H.id)},Q=()=>{M(!0)},[P,U]=A.useState(!1),te=s.useUpdateResource(s.ResourceType.DASHBOARD);async function le(){const X=ss(d);U(!0);const V={template:X};te.mutate({resourceId:X.id,data:V},{onSuccess:()=>{U(!1),s.ue.success("Dashboard saved!")},onError:()=>{U(!1),s.ue.error("Failed to save dashboard")}})}async function Y(){if(j(!0),!i||!u)return;const X=ss(d),V=JSON.stringify(X),H={...u,template:V,filterValues:T};await ys(H,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),O==null||O(X),j(!1)}if(I)return null;const q=(u==null?void 0:u.name)||d.title,oe=$&&$.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),ie=C&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[oe&&e.jsxs(e.Fragment,{children:[ie&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>z(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>N(!0),className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Aa,{className:"h-4 w-4"})})]}),!I&&o&&e.jsx(s.Label,{children:q})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(Ua,{className:"h-4 w-4"})}),!I&&o&&e.jsx(an,{}),!I&&o&&e.jsx(it,{}),!I&&o&&((pe=_==null?void 0:_.permissions)==null?void 0:pe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(Ka,{className:"h-4 w-4"})}),m&&!I&&se&&r&&o&&e.jsx(sn,{}),!I&&se&&r&&o&&e.jsx(tn,{}),m&&!I&&se&&u&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:Y,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!I&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:G,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!I&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:Q,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!I&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),R(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),W&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:P,onClick:le,size:"sm",children:[P?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),P?"Saving...":"Save"]}),!E&&!I&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>k(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!I&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>R(!v),size:"sm",variant:"ghost",children:e.jsx(Pe,{className:"h-4 w-4"})})}),!I&&r&&e.jsx(Qa,{}),!I&&e.jsx(vt,{isOpen:f,onClose:()=>N(!1)}),x&&Z&&e.jsx(ls,{resource:Z,resourceType:s.ResourceType.DASHBOARD,onClose:()=>b(!1)})]})]})}function Pn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:u,showNone:d=!1}){const m=Ee.useRef(null),[h,p]=Ee.useState(!1),[g,j]=Ee.useState("100%"),x=d?[...n||[],{id:"none",name:"None"}]:n;Ee.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function b(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(T=>T.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,T){r(T),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{className:"mr-2",children:u}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:b()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(nt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:T=>f(T,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Be({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:u,disabled:d=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function p(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(da,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:d,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",u),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(nt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,b)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},b))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Pn,{icon:p(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():j()})})}function zn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),l=s.useEditorStore(x=>x.selectedSchemaName),o=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:u,connectionType:d}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,b){var I;const f=s.createSqlGenConfig(x,i,b),N=(I=u==null?void 0:u.find(C=>C.id===c))==null?void 0:I.name;m(f);const T=s.getSql(f,s.fmt(l||""),s.fmt(r),N||"",d,o||"");T&&(h(T),p(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function _n({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(_n,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Vn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Un({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||u(m)||d(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Vn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Nt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",as="sortable-group-by",vs="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",Ts="sortable-order-by";function Gn(){const t=s.useDndStore(D=>D.insertIndex),n=s.useEditorStore(D=>{var M;return((M=D.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(D=>{var M;return((M=D.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(D=>{var M;return((M=D.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(D=>{var M;return((M=D.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(D=>{var M;return((M=D.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:u,setPreviewMetricColumns:d,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:b}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),I=D=>{var L;const{active:M,over:R}=D;if(((L=M.data.current)==null?void 0:L.type)==="column"&&R){const B=R.id,z=f.find(se=>se.column_name===M.id);if(!z)return;const $=s.isNumberDataType(z.data_type),_=s.isTextDataType(z.data_type),Z=s.isDateDataType(z.data_type);if(_||Z){if(n.some(W=>W.id===B)){const W=n.findIndex(G=>G.id===B);c(W);const J=n.filter(G=>G.id!==us.id);J.splice(W,0,us),u(J)}else if(R.id===Ie){c(n.length);const W=[...n,us];u(W),d(a),m(r)}}if(_||Z){if(o.some(W=>W.id===B)){const W=o.findIndex(G=>G.id===B);c(W);const J=o.filter(G=>G.id!==ms.id);J.splice(W,0,ms),h(J)}else if(R.id===Me){c(o.length);const W=[...o,ms];h(W),u(n),d(a),m(r)}}if($||_){if(a.some(W=>W.id===B)){console.log("isOverMetricSortable",B);const W=a.findIndex(G=>G.id===B);c(W);const J=a.filter(G=>G.id!==hs.id);J.splice(W,0,hs),d(J)}else if(R.id===Ae){c(a.length);const W=[...a,hs];d(W),m(r),u(n),h(o)}}if(S(z)){if(r.some(W=>W.id===B)){const W=r.findIndex(G=>G.id===B);c(W);const J=r.filter(G=>G.id!==xs.id);J.splice(W,0,xs),m(J)}else if(R.id===Ns){c(r.length);const W=[...r,xs];m(W),d(a),u(n),h(o)}}}else u(n),d(a),m(r),h(o)};function C(D){i(D.active.id),c(null),u(n),d(a),m(r),h(o)}function S(D){return!r.some(M=>M.name===D.column_name)}function y(D,M="SUM"){const{column_name:R,data_type:L}=D,B=[...a],z=t!==null?t:a.length,$={...D,id:Ne(R),name:R,label:He(R,M),type:L,role:"metric",aggregate:M};B.splice(z,0,$),g(B)}function E(D){const M=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const R=[...o],L=t!==null?t:o.length;let B;M?B={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:B={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ve(D.column_name,"month"),granularity:"month"},R.splice(L,0,B),b(R)}function v(D){const M=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const R=[...n],L=t!==null?t:n.length;let B;M?B={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:B={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ve(D.column_name,"month"),granularity:"month"},R.splice(L,0,B),p(R)}function O(D){const M=[...r],R=t!==null?t:r.length,L={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,sql:s.getDefaultFilterSql(D.data_type,N,s.fmt(D.column_name)),role:"filter"};M.splice(R,0,L),j(M)}function k(D){var B,z,$,_,Z,se,W,J;const{active:M,over:R}=D,L=M.data.current;if((L==null?void 0:L.type)==="column"&&R){const G=f.find(te=>te.column_name===M.id);if(!G)return;const Q=s.isNumberDataType(G.data_type),P=s.isTextDataType(G.data_type),U=s.isDateDataType(G.data_type);(P||U)&&(R.id===Ie||((B=R.data.current)==null?void 0:B.type)===as)&&v(G),(P||U)&&(R.id===Me||((z=R.data.current)==null?void 0:z.type)===ns)?E(G):(Q||P)&&(R.id===Ae||(($=R.data.current)==null?void 0:$.type)===vs)?(Q&&y(G),P&&y(G,"COUNT")):S(G)&&(R.id===Ns||((_=R.data.current)==null?void 0:_.type)===Cs)&&O(G)}if(R&&((Z=R.data.current)==null?void 0:Z.type)===as&&n.some(G=>G.id===M.id)){const G=n.findIndex(P=>P.id===M.id),Q=n.findIndex(P=>P.id===R.id);if(G!==-1&&Q!==-1&&G!==Q){const P=[...n],[U]=P.splice(G,1);P.splice(Q,0,U),p(P)}}if(R&&((se=R.data.current)==null?void 0:se.type)===ns&&o.some(G=>G.id===M.id)){const G=o.findIndex(P=>P.id===M.id),Q=o.findIndex(P=>P.id===R.id);if(G!==-1&&Q!==-1&&G!==Q){const P=[...o],[U]=P.splice(G,1);P.splice(Q,0,U),b(P)}}if(R&&((W=R.data.current)==null?void 0:W.type)===vs&&a.some(G=>G.id===M.id)){const G=a.findIndex(P=>P.id===M.id),Q=a.findIndex(P=>P.id===R.id);if(G!==-1&&Q!==-1&&G!==Q){const P=[...a],[U]=P.splice(G,1);P.splice(Q,0,U),g(P)}}if(R&&((J=R.data.current)==null?void 0:J.type)===Cs&&r.some(G=>G.id===M.id)){const G=r.findIndex(P=>P.id===M.id),Q=r.findIndex(P=>P.id===R.id);if(G!==-1&&Q!==-1&&G!==Q){const P=[...r],[U]=P.splice(G,1);P.splice(Q,0,U),j(P)}}F(D),i(null),c(null),u(n),d(a),m(r),h(o)}function F(D){const{active:M,over:R}=D,L=M.data.current;if((L==null?void 0:L.type)===Ts&&R){const B=l.findIndex($=>Ye($.columnId)===M.id),z=l.findIndex($=>Ye($.columnId)===R.id);if(B!==-1&&z!==-1&&B!==z){const $=[...l],[_]=$.splice(B,1);$.splice(z,0,_),x($)}}}function w(){i(null),c(null),u(n),d(a),m(r)}return{handleDragOver:I,handleDragEnd:k,handleDragStart:C,handleDragCancel:w,sensors:T}}function Ne(t){return`${t}-${s.v4()}`}function He(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ye(t){return`${Ts}-${t}`}function Ve(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function Yn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function $n({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),u=s.useEditorStore(B=>B.sqlGen),d=s.useEditorStore(B=>B.isDevMode);s.useEditorStore(B=>B.selectedConnectionId);const m=s.useEditorStore(B=>{var z,$;return($=(z=B.card)==null?void 0:z.queryConfig)==null?void 0:$.metricColumns});s.useEditorStore(B=>{var z,$;return($=(z=B.card)==null?void 0:z.queryConfig)==null?void 0:$.groupByColumns});const h=s.useEditorStore(B=>B.selectedDatabaseName);s.useEditorStore(B=>B.selectedSchemaName),s.useEditorStore(B=>B.selectedTableName);const p=s.useEditorStore(B=>B.selectedDatamodelId);s.useDashboardStore(B=>B.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:b,setCardSql:f,setRunSql:N,setSqlGen:T,setIsShowingVisual:I}=s.useEditorActions(),{connectionType:C,modelItems:S,selectedDatamodelName:y}=s.useEditorAside();function E(B){var z;if(d){const $=s.createSqlGenConfig(B,u);T($);const _=(z=S==null?void 0:S.find(se=>se.id===p))==null?void 0:z.name,Z=s.getSql($,s.fmt(t),s.fmt(n),_||"",C,h||"");Z&&(f(Z),N(!0))}if(!d){if(s.isTextDataType(B.data_type))if(m&&m.length>0){const $={...B,role:"groupby",id:Ne(B.column_name),name:B.column_name,type:B.data_type};b($)}else{const $={...B,role:"metric",id:Ne(B.column_name),name:B.column_name,label:He(B.column_name,"COUNT"),type:B.data_type,aggregate:"COUNT"};x($)}if(s.isDateDataType(B.data_type)){const $={...B,role:"groupby",id:Ne(B.column_name),name:B.column_name,type:B.data_type,label:Ve(B.column_name,"month"),granularity:"month"};b($)}if(s.isNumberDataType(B.data_type)){const $={...B,role:"metric",id:Ne(B.column_name),name:B.column_name,label:He(B.column_name,"SUM"),type:B.data_type,aggregate:"SUM"};x($)}}}function v(){const B=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:y,connectionType:C,databaseName:h||""});I(!1);const z=C==="MSSQL"?`SELECT top 10 * FROM ${B}`:`SELECT * FROM ${B} LIMIT 10`;f(z),N(!0)}function O(){const B=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:y,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${B}`),N(!0)}const k=(a==null?void 0:a.filter(B=>B.column_name.toLowerCase().includes(l.toLowerCase())))||[],F=B=>s.isNumberDataType(B.data_type)?"number":"text",w=c==="all"?k:k.filter(B=>F(B)===c),D=k.filter(B=>F(B)==="text").length,M=k.filter(B=>F(B)==="number").length;function R(B){return d?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>E(B),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{dataType:B.data_type}),e.jsx("span",{children:B.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(B.data_type)&&e.jsx(zn,{column:B})})]}):e.jsx(Un,{onClick:E,column:B})}function L(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:v,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Ia,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((B,z)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},z))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[d&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:L()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:B=>o(B.target.value)})]}),k.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:B=>i(B),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:k.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[w.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),w.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:w==null?void 0:w.map(B=>e.jsx("div",{children:R(B)},B.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ct({ColumnsComponent:t,type:n}){var H;const[a,r]=A.useState(!1),l=s.useEditorStore(ee=>ee.card),o=s.useEditorStore(ee=>ee.selectedConnectionId),c=s.useDashboardStore(ee=>ee.showFilters),i=s.useEditorStore(ee=>ee.selectedDatamodelId),u=s.useEditorStore(ee=>ee.selectedDatabaseName),d=s.useEditorStore(ee=>ee.selectedSchemaName),m=s.useEditorStore(ee=>ee.selectedTableName),h=s.useEditorStore(ee=>ee.isDevMode),{setSelectedTableName:p,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:x,modelItems:b,schemaItems:f,databaseItems:N,tableItems:T,columns:I,isConnectionsLoading:C,isModelsLoading:S,isConnectionsError:y,isModelsError:E,isDatabasesLoadingOrFetching:v,isDatabaseError:O,isSchemaLoadingOrFetching:k,isSchemaError:F,isColumnsError:w,isColumnsLoadingOrFetching:D,isTableLoadingOrFetching:M,isTableError:R,connectionType:L,isNonDbConnection:B,refetchDatabases:z,refetchModels:$,refetchSchemas:_,refetchTables:Z,refetchColumns:se,refetchConnections:W,handleConnectionChange:J,handleDatabaseChange:G,handleSchemaChange:Q,handleDatamodelChange:P,handleTableChange:U,tableName:te,schemaName:le}=s.useEditorAside(),{data:Y,refetch:q}=s.useDashboardCardQuery(l);function ae(){return t?t(le,te,I):e.jsx($n,{schemaName:le,tableName:te,columns:I,status:D?"Loading...":w?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ie(ee){ee===!0?Y&&(j(Y.userSql),setTimeout(()=>{q()},100)):j(""),g(ee)}function ue(){if(!o||L==="S3"||L==="API")return null;if(!i||i==="none")return e.jsx(Be,{refetch:z,showNone:!0,onChange:G,isError:O,isLoading:v,items:N,value:u||"",title:"Database",type:"combobox"})}function xe(){if(o&&!B&&(!u||u==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function pe(){if(!o||L==="S3"||L==="API")return null;if(!u||u==="none")return e.jsx(Be,{refetch:$,showNone:!0,onChange:P,isError:E,isLoading:S,items:b,value:i||"",title:"Model",type:"combobox"})}function X(){return!o||L==="S3"||L==="API"||!u||u==="none"?null:e.jsx(Be,{refetch:_,onChange:Q,isError:F,isLoading:k,items:f,value:d||"",title:"Schema",type:"combobox"})}function V(){function ee(){let ne=!1;return L==="API"?(ne=!1,ne):((L==="S3"||o&&u&&u!=="none"&&d)&&(ne=!0),ne)}return ee()?e.jsx(Be,{refetch:Z,onChange:U,isError:R,items:T,isLoading:M,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Be,{refetch:W,items:x,title:"Connection",value:o||"",onChange:J,isLoading:C,isError:y,type:"combobox",connectionTooltip:((H=x==null?void 0:x.find(ee=>ee.id===o))==null?void 0:H.type)||""}),ue(),xe(),pe(),X(),V()]})]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:ie,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ma,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function St({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ra,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function wt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function u(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(St,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(ba,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Dt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(ha,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(wt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function qn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function kt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),l=s.useEditorStore(x=>x.card),o=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:u,setRunSql:d}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),p=r.cards.find(x=>x.id===o),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const x=m.current.getModel();x&&(h.current[l.id]=x);let b=h.current[o];if(!b){const f=g();b=c.editor.createModel(f,t),h.current[o]=b}m.current.setModel(b)}u(o,l),d(!0)}},[o,l,u,c,d,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=a==="system"?x:a;c.editor.defineTheme("default",{base:b==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":b==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,b){if(m.current=x,!h.current[l.id]){const f=x.getModel(),N=g();h.current[l.id]=f||(b==null?void 0:b.editor.createModel(N,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Hn(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=kt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Wn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=kt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Kn({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Es({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ds(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=ks();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Jn(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(d=>d.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=ks(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),u=()=>{const d=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:d}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:u,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Is(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(u=>u.tempQueryData),l=s.useEditorStore(u=>u.onClose),o=s.useEditorStore(u=>u.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:u,queryData:d}=r;u&&d&&a.setQueryData(u,d)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.tempQueryData),l=s.useEditorStore(b=>b.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:u,setCardCustomCfg:d,setCardPreferences:m,updateDataSource:h,clearQueryConfig:p,setCardConfig:g,setCardType:j}=s.useEditorActions();function x(){const b=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:b}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),g(void 0),u(""),d(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qn(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(_=>_.frame);const o=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const c=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const i=s.useEditorStore(_=>{var Z;return(Z=_==null?void 0:_.card)==null?void 0:Z.sql}),u=s.useEditorStore(_=>{var Z;return(Z=_==null?void 0:_.card)==null?void 0:Z.python}),{sheetFilterValues:d}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:x,setCardType:b,setCardPython:f,runAssistant:N,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const I=s.useEditorStore(_=>_.runSql),C=s.useEditorStore(_=>_.actions.setRunSql),S=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:y,isLoading:E,isFetching:v,isSuccess:O,isError:k,error:F,errorSql:w,queryKey:D,refetch:M,errorMessage:R}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:_}=s.getKeys(y.records);h(_)}},[y,h,j]),A.useEffect(()=>{(E||v)&&S(!0),(k||O)&&S(!1),k&&(h([]),j(""))},[E,v,y,j,k,O,S,h,F]),A.useEffect(()=>{I&&(t.getQueryData(D)||M(),C(!1))},[I,M,C,D,t]);async function L(){const _=`Can you help me debug this query?
342
-
343
- Error:
344
-
345
- ${R}
346
-
347
- Error SQL:
348
-
349
- ${w}
350
-
351
- Query:
352
-
353
- ${i}
354
-
355
- ${u?`Python:
356
- ${u}`:""}
357
- `;N(_)}function B(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Kn,{jsonString:JSON.stringify(d,null,2)})})}),d&&d.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function z(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Hn,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Wn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function $(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:E||v,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[E||v?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Dt,{errorSql:w,sql:y==null?void 0:y.sql,error:R,onDebugWithAssistant:L}),e.jsx(os,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:_=>a(_),className:"h-8",size:"sm",variant:"outline",children:e.jsx(qn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{}),e.jsx(Es,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[z(),B()]}),$()]})}const Xn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:rs}];function Zn({className:t}){const n=s.useEditorStore(u=>u.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=u=>{var m;const d=u;if(d==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:d,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(d);const h={...n,type:d};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Xn.map(u=>{const d=u.icon;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:u.value,id:`table-type-${u.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${u.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all","hover:bg-muted","peer-data-[state=checked]:bg-background peer-data-[state=checked]:shadow-sm"),children:[e.jsx(d,{className:"h-3.5 w-3.5"}),u.label]})]},u.value)})})})}function er({card:t}){var N,T,I,C,S,y,E,v,O,k,F;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(w=>w.themeStyle),u={colors:((T=(N=i==null?void 0:i.chart)==null?void 0:N.dataset)==null?void 0:T.backgroundColor)||[]};(I=t.customCardPreferences)!=null&&I.inputData;const{getCard:d}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),m=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=A.useCallback((w,D)=>{l(M=>({...M,[w]:D}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const x=d((E=t.customCardPreferences)==null?void 0:E.componentName);function b(w){a(w)}const f=Object.keys(((v=t.customCardPreferences)==null?void 0:v.dataInputCardIds)||{}).map(w=>{var R,L,B;const D=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,M=(B=h==null?void 0:h.cards)==null?void 0:B.find(z=>z.id===D);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:u,settings:(O=t.customCardPreferences)==null?void 0:O.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(w=>{var R,L,B;const D=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,M=(B=h==null?void 0:h.cards)==null?void 0:B.find(z=>z.id===D);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:b,onDataChange:j,dataInputIndex:w,card:M},M.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:u,onDataChange:j,settings:f.map(w=>{var D;return(D=w==null?void 0:w.customCardPreferences)==null?void 0:D.settings}),data:f.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(F=t.customCardPreferences)==null?void 0:F.componentName)})}function Tt({className:t,...n}){var E;const a=s.useEditorStore(v=>v.card),r=s.isExplorerCard(a),l=((E=a.customCardPreferences)==null?void 0:E.showCardHeader)??!0,o=s.useEditorStore(v=>v.frame),c=s.useDashboardStore(v=>v.dashboard.filters),i=s.useEditorStore(v=>v.actions.setRunSql),{updateFilter:u}=s.useDashboardActions(),d=c==null?void 0:c.find(v=>v.id===o.filterId),{data:m,isLoading:h,isFetching:p,errorMessage:g,pagination:j}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:b}=s.useEditorActions(),{data:f}=s.useTopoJson(a),N=A.useMemo(()=>{var v;return a.type!=="pivotTable"||!((v=m==null?void 0:m.records)!=null&&v.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),T=s.usePivotTableConfig(a,N),I=(v,O)=>{var F,w;const k={...a,paginationConfig:{page:v+1,pageSize:O}};x(k),b(k),a.sql&&((w=(F=a.preferences)==null?void 0:F.tablePrefs)!=null&&w.enableDevModePagination)&&i(!0)},C=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function S(v){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(er,{card:v})})}function y(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!p)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return S(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:j,onPaginationChange:I,isLoading:h||p})});if(a.type==="pivotTable"&&T)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:T.data,options:T.options,onAggregationChange:v=>{const O=s.handleAggregationChange(v,a.config),k={...a,config:O};x(k),b(k)},onAggregationLabelChange:v=>{const O=s.handleAggregationLabelChange(v,a.config),k={...a,config:O};x(k),b(k)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:j,onPaginationChange:I,onAggregationChange:v=>{const O=s.handleAggregationChange(v,a.config),k={...a,config:O};x(k),b(k)},isLoading:h||p})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:v=>x({...a,title:v}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Zn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:v=>x({...a,description:v}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:d.title||d.column,onSave:v=>u({...d,title:v}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:y()})]})}const ps=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),sr=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),tr=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"javascript",value:t,onChange:l})})]}),ar=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function nr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:b}=s.useEditorActions(),f=C=>{var S,y;return JSON.stringify({...C,data:{...C.data,datasets:(y=(S=C.data)==null?void 0:S.datasets)==null?void 0:y.map(E=>({...E,data:[]}))}},null,2)},N=()=>{var S,y;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(C){r(f(C)),i(((y=m.preferences)==null?void 0:y.customVisualCode)||"");const E=s.merge(C,h);o(f(E))}},T=()=>{try{if(c&&b(c),l){const C=JSON.parse(l),S=s.getObjectDiff(JSON.parse(a),C);x(S),d("")}}catch{d("Invalid JSON configuration")}},I=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:N,className:I?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(sr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(tr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(ar,{error:u,hasCardCustomConfig:!!h,onReset:()=>{o(a),x(null)},onApply:T,onClose:()=>n(!1)})]})]})}function is(t){const[n,a]=A.useState(null);return n}function Et(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:n,isLoading:a,isFetching:r,isError:l}}function It(){const{data:t,isLoading:n,isError:a}=Et(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,u)=>{var d;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((d=t==null?void 0:t.plugins)!=null&&d[u])){const m=t.plugins[u],h=i.data.visuals.map(p=>({name:p.name,pluginName:m.label,componentType:p.componentType,pluginType:m.type,icon:p.icon,chartType:p.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function rr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=It(),u=A.useCallback((d,m)=>{n(null),a({}),r(d),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((d,m)=>e.jsx(lr,{text:d.name,onClick:()=>u("custom",d),icon:d.icon},`${d.url}-${d.name}-${m}`))})]})}const lr=({text:t,icon:n,onClick:a})=>{const r=is(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function At({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function u(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const d=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:d,tooltip:"Table",onClick:()=>u("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bar Chart",onClick:()=>u("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Line Chart",onClick:()=>u("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Bar Chart",onClick:()=>u("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Line Chart",onClick:()=>u("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Scatter Chart",onClick:()=>u("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bubble Chart",onClick:()=>u("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Pie Chart",onClick:()=>u("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Doughnut Chart",onClick:()=>u("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Funnel Chart",onClick:()=>u("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Radar Chart",onClick:()=>u("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Polar Area Chart",onClick:()=>u("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Tornado Chart",onClick:()=>u("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>u("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"KPI",onClick:()=>u("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Text",onClick:()=>u("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>u("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Custom",onClick:()=>u("custom"),className:"h-10 p-4",children:e.jsx(qe,{className:s.cn("size-5",n)})})]})}function or({chartType:t,className:n,customIcon:a,componentName:r}){const l=is();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ye,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(qe,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Mt({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(or,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(At,{onChartTypeChange:()=>a(!1)}),e.jsx(rr,{onChartTypeChange:()=>a(!1)})]})]})}function ir({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function u(){t&&!i.current&&navigator.clipboard.writeText(t)}function d(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),u())}function m(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const g=p.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:u,onKeyDown:d,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function cr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(Gs,{className:"size-4"}):e.jsx(Us,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Gs,{className:"size-4"}):e.jsx(Us,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function Lt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,u;return(u=(i=c.card)==null?void 0:i.preferences)==null?void 0:u.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],u=(c.indexOf(r)+1)%c.length;l(c[u])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(cr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(rs,{className:"size-4"}),r==="x"&&e.jsx(xa,{className:"size-4"}),r==="y"&&e.jsx(_a,{className:"size-4"}),r==="none"&&e.jsx($a,{className:"size-4"})]})]}):null}function dr(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},i=j=>{j.preventDefault()},u=(j,x)=>{const b=j.dataTransfer.getData("tabIndex");if(b===x.toString())return;const f=Array.from(t.cards),[N]=f.splice(parseInt(b),1);f.splice(x,0,N),a({...t,cards:f})};function d(j){const x=t.cards.filter(N=>N.id!==j),b=x[0],f={...t,cards:x,activeCardId:b.id};a(f),r(b.id),l(b)}function m(j,x){const b={...t,cards:[...t.cards,x],activeCardId:j.id};a(b),r(x.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,j)}function p(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,x)}function g(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const b=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:b}),o({...x,displayTab:b})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ja,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:b=>c(b,x),onDragOver:i,onDrop:b=>u(b,x),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:b=>{l({...n,tabTitle:b}),o({...n,tabTitle:b})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>d(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(fa,{className:"h-4 w-4"})})]})})}function Rt(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:u}=s.useEditorActions(),{data:d,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function p(x){const b=t.cards.find(f=>f.id===x);if(b!=null&&b.sql){r||i(!0),o(x);return}if(b!=null&&b.queryConfig){r&&i(!1),g(x),o(x);return}r||g(x),o(x)}function g(x){const b={...t,cards:t.cards.map(N=>N.id===n.id?n:N),activeCardId:x};l(b);const f=b.cards.find(N=>N.id===x);f.sql&&u(!0),c(f)}function j(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:d==null?void 0:d.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:d==null?void 0:d.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:j()},x.id)),e.jsx(dr,{})]})}function Qe({children:t}){var I,C;s.useEditorStore(S=>S.frame);const n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:u,runAssistant:d,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:g,isFetching:j,errorMessage:x,refetch:b}=s.useDashboardCardQuery(n);function f(){const S=JSON.stringify(p==null?void 0:p.records,null,2),y=new Blob([S],{type:"application/json"}),E=URL.createObjectURL(y),v=document.createElement("a");v.href=E,v.download=`${n.title}.json`,v.click()}function N(){const y=[Object.keys(p==null?void 0:p.records.reduce((k,F)=>({...k,...F}),{})).join(","),...((p==null?void 0:p.records)||[]).map(k=>Object.values(k).join(","))].join(`
358
- `),E=new Blob([y],{type:"text/csv"}),v=URL.createObjectURL(E),O=document.createElement("a");O.href=v,O.download=`${n.title}.csv`,O.click()}function T(){const S=`Can you get the documentation for ${n.type} chart?`;d(S)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Mt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(ca,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(nr,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:N,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(ya,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Lt,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((C=(I=n.preferences)==null?void 0:I.tablePrefs)==null?void 0:C.enableDevModePagination)??!1,onCheckedChange:S=>{var y;h({...n.preferences,tablePrefs:{...(y=n.preferences)==null?void 0:y.tablePrefs,enableDevModePagination:S}}),b()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(mr,{})]}),r?e.jsx(Rt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(ur,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[]}),x&&e.jsx(ir,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ur(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function mr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function hr(){var x,b;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=Et(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:u}=s.useCustomVisual((t==null?void 0:t.url)||""),d=(x=u==null?void 0:u.visuals)==null?void 0:x.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,N){if(!t)return;const I={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:I})}function h(f){var T,I;const N=(T=l==null?void 0:l.cards)==null?void 0:T.filter(C=>{var S;return((S=C==null?void 0:C.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(I=f==null?void 0:f.dataInputs)==null?void 0:I.map((C,S)=>{var y,E;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((E=(y=t==null?void 0:t.dataInputCardIds)==null?void 0:y[S])==null?void 0:E.cardId)||"",onValueChange:v=>m(S,v)})]},S+Math.random())})})}function p(f,N,T=[],I=""){var C,S;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[N])||I,onChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:y.target.value}})}},N):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:T,value:((S=t==null?void 0:t.settings)==null?void 0:S[N])||I,onValueChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:y}})}}):null:null}function g(f){const N=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([T,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:I.title}),p(I.ui,T,I.options,I.defaultValue)]},T))})}function j(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ce,{icon:e.jsx(ia,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(pa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((b=r==null?void 0:r.customCardPreferences)==null?void 0:b.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[d&&d.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(d)})]}),d&&d.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(d)})})]})]})]})}function Oe(){const[t,n]=A.useState([]),a=s.useEditorStore(d=>d.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(d=>d.actions),o=s.useEditorStore(d=>d.queryResultColumns);s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(d,m){var h,p;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:d,expression:""}]}):l({...a,onClickFilter:[{columnIndex:d,expression:""}]}):(l({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==d)}),n(g=>{const j=[...g];return j[d]=!1,j}))}function i(d,m){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===d?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function u(d){var m,h,p,g;if(t!=null&&t[d]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===d))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===d))==null?void 0:g.expression,onChange:j=>i(d,j),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:o==null?void 0:o.map((d,m)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:d}),e.jsx("div",{className:"flex items-center gap-2",children:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[m]=!g[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},d)})})}function xr({idx:t}){var i;const n=s.useEditorStore(u=>{var d;return(d=u.card)==null?void 0:d.preferences}),a=s.useEditorStore(u=>{var d;return(d=u.card.preferences)==null?void 0:d.datasetOptions}),r=s.useEditorStore(u=>u.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(u=>u.idx===t);function c(u,d){(u==="end"||u==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:d,datalabels:m}]});else{const h={...o};h.datalabels=m;const p=a==null?void 0:a.map(g=>g.idx===d?h:g);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(lt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ka,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function pr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Ot(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var d,m,h;return(h=(m=(d=u==null?void 0:u.card)==null?void 0:d.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=pr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(u=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:u,children:Bt(u)},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((u,d)=>e.jsx(Ft,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:u,idx:d},u))})]})]})}function Bt(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ft({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,p;return(p=(h=m.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:u}=s.useEditorStore(m=>m.actions);function d(m){if(!i)u({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===n?h:g);u({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(cs,{className:"max-w-[100px]",title:t,children:Bt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>d("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>d("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>d("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xr,{idx:n})]})]})}function As(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:d,tableName:m,connectionType:h}=s.useEditorAside();function p(g,j="dashboard",x){var E;const b=s.fmt(g.column_name),f=s.fmt(a||""),N=s.fmt(r||""),T=s.fmt(m);let I=s.getQualifiedTableName({schemaName:N,tableName:T,connectionType:h,databaseName:f}),C=`${I}.${b}`;const S=(E=d==null?void 0:d.find(v=>v.id===n))==null?void 0:E.name;n&&n!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${S}.${b}`,I=`${s.DATAMODEL_NAMESPCACE}.${S}`),x!=null&&x.qualifiedFieldName&&(C=x.qualifiedFieldName),x!=null&&x.entityName&&(I=x.entityName);const y=o==null?void 0:o.find(v=>v.column===C&&v.table===T&&(v.database===f||v.database===a));if(y)u(y.id),i(y.id);else{const v=s.v4();return m==="api"&&t?(c({location:j,id:v,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),v):(c({id:v,location:j,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),v)}}return{assignFilter:p}}function Ue(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=As();function o(i){const u=l(i,"frame");a({...n,filterId:u})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(fr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function fr({columns:t,onSelect:n}){var c;const[a,r]=Ee.useState(!1),[l,o]=Ee.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:u=>{const d=u===l?"":u;o(d),r(!1),d&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function gr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Ot,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function jr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function Pt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const u={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},d={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...u}}};r(d)}function o(){var i,u,d;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,u,d;return e.jsx("div",{children:e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const br={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},yr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function vr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Nr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Pt,{}),e.jsx(Oe,{}),e.jsx(Ue,{})]})]})}function Nr(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(br,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(yr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Cr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,u){const d=[...t];d[c]={...d[c],[i]:u},n(d)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:u=>r(i,"start",u.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:u=>r(i,"end",u.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:u=>r(i,"color",u.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Sr(){var m,h,p,g,j;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),l=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.colorRanges})||[],u=s.useEditorStore(x=>x.actions.setColorRanges),d=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:x=>{var b,f,N;return l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",x,((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:x=>{var b,f,N;console.log("currency",x),l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,x==="none"?"":x,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),d.map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var b,f,N;return l(Number(x),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.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:x=>{var b,f,N;return l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Cr,{colorRanges:i,setColorRanges:u})]})]})}function wr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Sr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function fs({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Dr=[{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"}],kr=["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"],Tr=kr.map(t=>({label:t,value:t}));function Er(){var u,d,m,h,p,g,j,x,b,f,N,T,I,C,S,y,E,v;const t=s.useEditorStore(O=>O.card),n=(d=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:d.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(fs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),l({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Dr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:O=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Tr,value:((f=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((T=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:O=>{var k;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(C=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:S[0])||0,onChange:O=>{var k,F,w,D;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[Number(O.target.value),((D=(w=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((v=(E=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:v[1])||0,onChange:O=>{var k,F,w,D;l({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[((D=(w=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oe,{})]})}function Ir(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Xe({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Ir,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function Ar(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Ot,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function Mr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function zt({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,u]=A.useState(50),[d,m]=A.useState(t);A.useEffect(()=>{const b=Hs(t);if(b){const f=Ws(b.r,b.g,b.b);l(f.h),c(f.s),u(f.l),m(t)}},[t]);const h=b=>{l(b),g(b,o,i)},p=b=>{const f=b.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(b.clientX-f.left)/f.width)),T=Math.max(0,Math.min(1,(b.clientY-f.top)/f.height)),I=N*100,C=(1-T)*100;c(I),u(C),g(r,I,C)},g=(b,f,N)=>{const T=Rr(b,f,N),I=Lr(T.r,T.g,T.b);m(I)},j=b=>{if(m(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const f=Hs(b);if(f){const N=Ws(f.r,f.g,f.b);l(N.h),c(N.s),u(N.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(d)&&(n(d),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:b=>{b.buttons===1&&p(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:`${o}%`,top:`${100-i}%`,backgroundColor:d}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>h(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(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:d,onChange:b=>j(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:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:d}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function Hs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Lr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Ws(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const u=r-l;switch(c=i>.5?u/(2-r-l):u/(r+l),r){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Rr(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(d,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?d+(m-d)*6*h:h<.5?m:h<.6666666666666666?d+(m-d)*(.6666666666666666-h)*6:d),i=a<.5?a*(1+n):a+n-a*n,u=2*a-i;r=c(u,i,t+1/3),l=c(u,i,t),o=c(u,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Or=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function _t(){var T,I,C,S,y,E,v,O,k,F;const t=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>{var D;return(D=w.card)==null?void 0:D.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,u]=A.useState(null),[d,m]=A.useState(null),h=A.useMemo(()=>{var R,L,B,z,$,_,Z;if(!(l!=null&&l.records)||l.records.length===0)return[];const w=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",D=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns)&&t.config.pivotByColumns.length>0;if((w||D)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const se=new Set;return l.pivotSchema.forEach(W=>{W.alias&&se.add(W.alias)}),Array.from(se)}if(l.records.length>0){const se=l.records[0],W=Object.keys(se),J=new Set;(L=t==null?void 0:t.config)!=null&&L.groupByColumns&&t.config.groupByColumns.forEach(P=>{J.add(P.label||P.name),J.add(P.alias||P.name)});const G=new Set;return(B=t==null?void 0:t.config)!=null&&B.metricColumns&&t.config.metricColumns.forEach(P=>{const U=P.alias||P.name;G.add(U),G.add(`${U}_count`),G.add(`${U}_sum`),G.add(`${U}_avg`),G.add(`${U}_min`),G.add(`${U}_max`);const te=P.entityName||P.qualifiedEntityName;te&&(G.add(`${te}_${U}`),G.add(`${te}_${U}_count`))}),W.filter(P=>!J.has(P)&&!G.has(P))}}if((D||w)&&!M&&(($=(z=t==null?void 0:t.config)==null?void 0:z.metricColumns)!=null&&$.length))return t.config.metricColumns.map(se=>se.alias||se.label||se.name);if((Z=(_=t==null?void 0:t.config)==null?void 0:_.groupByColumns)!=null&&Z.length){const se=t.config.groupByColumns[0],W=se.label||se.name,J=new Set;return l.records.forEach(G=>{const Q=G[W];Q!=null&&J.add(String(Q))}),Array.from(J)}return[]},[l,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const w={};h.forEach((D,M)=>{w[D]=s.getColorForValue(D,M,n==null?void 0:n.colorConfig)}),c(w)},[h,n==null?void 0:n.colorConfig,p]);const g=(w,D)=>{const M={...o,[w]:D};c(M);const R={...n||{},colorConfig:{segments:M}};a(R);const L={...t,preferences:R};r(L)},j=(w,D)=>{var $;const M=p[D%p.length],{[w]:R,...L}=(($=n==null?void 0:n.colorConfig)==null?void 0:$.segments)||{},B={...n||{},colorConfig:{segments:L}};a(B);const z={...t,preferences:B};r(z),c(_=>({..._,[w]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((y=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:y.length)||((v=(E=t==null?void 0:t.config)==null?void 0:E.pivotByColumns)==null?void 0:v.length):(k=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:k.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const w={...n||{},colorConfig:{segments:{}}};a(w);const D={...t,preferences:w};r(D);const M={};h.forEach((R,L)=>{M[R]=s.getColorForValue(R,L,void 0)}),c(M)},N=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((w,D)=>{const M=s.isDefaultColor(o[w],D),R=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===w,onOpenChange:L=>u(L?w:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[w]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((L,B)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[w]===L?"border-gray-900":"border-transparent"),style:{backgroundColor:L},onClick:()=>{g(w,L),u(null)},children:[B===D%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:L})]},`default-${B}`))})]}),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:Or.map((L,B)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[w]===L?"border-2 border-gray-900":L==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:L},onClick:()=>{g(w,L),u(null)},children:e.jsx("span",{className:"sr-only",children:L})},`preset-${B}`))})]}),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:()=>{m({value:w,color:o[w]}),u(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(w,D),u(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:w}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},w)})}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(zt,{color:d.color,onColorChange:w=>{g(d.value,w),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,u]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const d=()=>{n(o),u(!1)},m=()=>{c(t??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),u(!0)},onFocus:()=>u(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?d():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:d,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Br=["auto","number","currency","percent","scientific","date"],Fr=[{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"}],Pr=[{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"}],zr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ms({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,u)=>{n({...t,[i]:u})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Br.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":zr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Fr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Ks({axis:t,label:n,type:a,config:r,onChange:l}){var h,p,g,j,x,b,f,N,T,I,C,S;const o=(y,E)=>{l({...r,[y]:E})},c=(y,E)=>{var v,O;l({...r,name:{enabled:y==="enabled"?E:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,text:y==="text"?E:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(y,E)=>{var v,O;l({...r,labels:{enabled:y==="enabled"?E:((v=r==null?void 0:r.labels)==null?void 0:v.enabled)??!0,rotation:y==="rotation"?E:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},u=(y,E)=>{l({...r,scale:{...r==null?void 0:r.scale,[y]:E===""?"auto":Number(E)}})},d=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:y=>o("enabled",y),onClick:y=>y.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:y=>c("enabled",y)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:y=>c("text",y),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:y=>o("position",y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":s.titleCase(y)},y))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:y=>i("enabled",y)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((b=r==null?void 0:r.labels)==null?void 0:b.rotation)||"auto"),onValueChange:y=>i("rotation",y==="auto"?"auto":Number(y)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":`${y}°`},y))})]})]})]}),a==="value"&&e.jsx(Ms,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:y=>l({...r,formatOptions:y}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:y=>u("min",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.max)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.max)===void 0?"":String(r.scale.max),onSave:y=>u("max",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:y=>u("stepSize",y),className:""})})]})]})]})]})]})}function Vt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const d={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(d);const m={...t,preferences:d};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Ks,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Ks,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Ut(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var m,h,p,g;return(g=(p=(h=(m=d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(d,m)=>{const h={...n,[d]:m};a(h)},i=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:d=>c("display",d)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:d=>c("position",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:d=>c("align",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]})]})]})})]})}function Gt(){var E,v,O,k,F,w,D,M,R;const t=s.useEditorStore(L=>L.card),n=s.useEditorStore(L=>{var B,z;return(z=(B=L.card)==null?void 0:B.preferences)==null?void 0:z.dataLabelsConfig}),a=s.useEditorStore(L=>{var B;return(B=L.card)==null?void 0:B.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((E=a==null?void 0:a.chartOptions)==null?void 0:E.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!i,d=(O=(v=a==null?void 0:a.chartOptions)==null?void 0:v.plugins)==null?void 0:O.datalabels,m=(d==null?void 0:d.display)!==!1&&((d==null?void 0:d.anchor)||(d==null?void 0:d.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,p=(L,B)=>{const z={...n,[L]:B},$={...t.preferences||{},dataLabelsConfig:z};r($);const _={...t,preferences:$};l(_)},g=(L,B)=>{const z={...n,font:{...n==null?void 0:n.font,[L]:B}},$={...t.preferences||{},dataLabelsConfig:z};r($);const _={...t,preferences:$};l(_)},j=(L,B)=>{const z={...n,formatOptions:{...n==null?void 0:n.formatOptions,[L]:B}},$={...t.preferences||{},dataLabelsConfig:z};r($);const _={...t,preferences:$};l(_)},b=(()=>{const L=t.type;return L==="stackedBar"||L==="stackedLine"||L==="pie"||L==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(B=>B!==b),"custom"];const N=()=>s.titleCase(b),T=["center","start","end"],I=["center","start","end","top","bottom"],C=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{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"}],y=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:L=>p("enabled",L)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:L=>p("position",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"?N():L==="custom"?"Custom (Advanced)":s.titleCase(L)},L))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:L=>p("showTotal",L)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:L=>p("anchor",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:L=>p("align",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(u?"auto":"none"),onValueChange:L=>p("format",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"&&u?"Auto (Use Axis)":L==="none"?"None (Raw Value)":s.titleCase(L)},L))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((k=n==null?void 0:n.formatOptions)==null?void 0:k.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:L=>j("decimalPlaces",Number(L)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:L=>j("currency",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((w=n==null?void 0:n.formatOptions)==null?void 0:w.useSuffix)??!1,onCheckedChange:L=>j("useSuffix",L)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((D=n==null?void 0:n.formatOptions)==null?void 0:D.locale)||"en-US",onValueChange:L=>j("locale",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:L=>g("size",Number(L)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((R=n==null?void 0:n.font)==null?void 0:R.weight)||"normal",onValueChange:L=>g("weight",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:L=>{L==="auto"&&p("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:L=>p("rotation",Number(L)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function _r(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(_t,{}),e.jsx(Vt,{}),e.jsx(Ut,{}),e.jsx(Gt,{})]})]})}const Vr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ur=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Gr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Yr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(_r,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Ar,{}));case"tornado":case"pyramid":return l(e.jsx(Xe,{docContent:Vr,cardType:a}));case"kpi":return e.jsx(wr,{});case"line":case"bar":return l(e.jsx(gr,{cardType:a}));case"range":return l(e.jsx(Xe,{docContent:Ur,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Xe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(jr,{cardType:a}));case"table":return e.jsx(Mr,{cardType:a});case"text":return e.jsx(Xe,{docContent:Gr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Er,{});case"custom":return e.jsx(hr,{});default:return l(e.jsx(vr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Yt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const $r=[{label:"Sum",value:"SUM",logo:e.jsx(rt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(va,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(ra,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function qr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=$r;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:He(t.name,l)};n(t.id,o)}return e.jsx(Yt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const Hr=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Wr({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:Ve(t.name,r)};n(t.id,l)}return e.jsx(Yt,{column:t,functions:Hr,onFunctionChange:r=>a(r),label:"Granularity"})}function Kr({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Ie||a===Ae||a===Me)&&(i=r);const u=i==null?void 0:i.filter(d=>d.column_name!==t.name);return u==null?void 0:u.map(d=>({id:d.column_name,value:d.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const u=r==null?void 0:r.find(d=>{var m;return d.column_name===((m=i[0])==null?void 0:m.id)});u&&n(u)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function $t({column:t}){const n=s.useEditorStore(u=>u.card.type),a=s.useEditorStore(u=>{var d,m;return(m=(d=u.card)==null?void 0:d.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(u=>u.label))||[],l=r==null?void 0:r.find(u=>u===t.label||u===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ft,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Pt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function Jr({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:u}=s.useEditorActions(),{attributes:d,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),x=p?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,b=s.isTextDataType(t.type);function f(S){const y=s.isNumberDataType(S.data_type),E=s.isTextDataType(S.data_type),v=s.isDateDataType(S.data_type),O=y?"number":E?"string":v?"date":"string";if(r===Ie){if(E){const k={id:t.id,name:S.column_name,type:O,role:"groupby"};c(t.id,k)}if(v){const k={id:t.id,name:S.column_name,type:O,role:"groupby",label:Ve(S.column_name,"month"),granularity:"month"};c(t.id,k)}}if(r===Me){if(E){const k={id:t.id,name:S.column_name,type:O,role:"groupby"};u(t.id,k)}if(v){const k={id:t.id,name:S.column_name,type:O,label:Ve(S.column_name,"month"),granularity:"month",role:"groupby"};u(t.id,k)}}if(r===Ae){const k={id:t.id,name:S.column_name,type:O,role:"metric",label:He(S.column_name,"SUM"),aggregate:y?"SUM":"COUNT"};i(t.id,k)}}function N(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx($t,{column:t})})}function T(){const S=s.isDateDataType(t.type);if(r===Ae)return e.jsx(qr,{column:t});if((r===Ie||r===Me)&&S)return e.jsx(Wr,{column:t})}function I(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&b}),children:e.jsx(Kr,{col:t,onChange:f,droppableId:r})})}function C(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ga,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...d,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[C(),T(),I()]}),l&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function gs({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,b;const{setNodeRef:c,isOver:i,over:u}=s.useDroppable({id:t}),d=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var N;return(N=f.card)==null?void 0:N.type}),h=i||((b=(x=u==null?void 0:u.data)==null?void 0:x.current)==null?void 0:b.type)===l,p=d?r:a,g=l===as?"Rows":l===ns?"Pivot Columns":"Columns";function j(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(f=>f.id===Nt.id?e.jsx(Qr,{},f.id):e.jsx(Jr,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function Qr(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function qt({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:u}=s.useSortable({id:n,data:{type:a}}),d=c?{opacity:u?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:d,children:t})}function Xr(){const t=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(la,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(N=>N.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function p(f,N){const T=g(f);return T?T.role==="metric"?N==="asc"?d:m:N==="asc"?i:u:null}function g(f){return c.find(N=>N.id===f)}function j(f){const N=t.find(T=>T.columnId===f);if(N){const T={...N,direction:N.direction==="asc"?"desc":"asc"};o(T)}}const x=f=>{r({columnId:f.id,direction:"asc"})};function b(f){const N=t.find(T=>T.columnId===f);N&&l(N)}return e.jsx(s.SortableContext,{items:t.map(f=>Ye(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>x(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var N,T;return e.jsx(qt,{id:Ye(f.columnId),type:Ts,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(cs,{className:"w-[175px] text-sm",children:((N=g(f.columnId))==null?void 0:N.label)||((T=g(f.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:p(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ye(f.columnId))})]})})}function Zr(){const t=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(b=>b.card.type),a=s.useDndStore(b=>b.previewGroupByColumns),r=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(b=>b.previewMetricColumns),o=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(b=>b.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:u,removeColumnFromPivotBy:d}=s.useEditorActions();function m(b){i(b)}function h(b){u(b)}function p(b){d(b)}let g="Group By",j="Metrics",x="Stack By";return n==="table"&&(g="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(At,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(gs,{onRemoveColumn:m,sortableType:as,id:Ie,label:g,columns:t,previewColumns:a}),e.jsx(gs,{onRemoveColumn:p,sortableType:ns,id:Me,label:x,columns:o,previewColumns:c}),e.jsx(gs,{onRemoveColumn:h,sortableType:vs,id:Ae,label:j,columns:r,previewColumns:l}),e.jsx(Xr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ls({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:u}=s.useEditorActions(),d=s.useEditorStore(h=>{var p,g;return(g=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(qt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),d&&e.jsx("button",{onClick:()=>u(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function el({column:t,sortableType:n}){const a=s.useDashboardStore(T=>T.themeStyle),r=s.useEditorStore(T=>{var I,C;return(C=(I=T.card)==null?void 0:I.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(T=>{var I,C;return(C=(I=T.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:C.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),u=A.useMemo(()=>{var T;return(T=r==null?void 0:r.find(I=>I.filterColumnName===t.name))==null?void 0:T.filterValue},[r,t.name]),d=A.useMemo(()=>Array.isArray(u)?u.map(T=>({id:T,value:T})):[],[u]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:g,isFetching:j,isError:x}=s.useFilterQuery(h),b=A.useMemo(()=>{var I;return h.column?(I=p==null?void 0:p.records)==null?void 0:I.map(C=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return C[S]===void 0&&(S=S.toLowerCase()),{id:C[S],value:C[S]}}):[]},[p,h.column]);function f(T){const I=T.map(C=>C.id);m(t.name,I)}function N(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(sl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:b,onChange:f,selectedOptions:d,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Ls,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function sl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function tl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:u}){const d=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:d==null?void 0:d.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:d==null?void 0:d.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:u,children:"Clear"})]})]})]})})}function al({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:u,isFetching:d,isError:m,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:b}=s.useEditorActions();function f(I){var S,y;const C={gte:(S=I==null?void 0:I.from)==null?void 0:S.toISOString(),lte:(y=I==null?void 0:I.to)==null?void 0:y.toISOString()};b(t.name,C)}function N(){b(t.name,null,!0),j(x)}function T(){return u||d?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(tl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:f,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Ls,{className:"w-72",id:t.id,sortableType:n,column:t,children:T()})}function nl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var j,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),u=s.useDndStore(b=>b.activeId),d={},m=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(b){const f=s.isDateDataType(b.type);return b.id===Nt.id?e.jsx(Ls,{id:b.id,sortableType:l,column:b,children:e.jsx(rl,{})},b.id):f?e.jsx(al,{droppableId:t,sortableType:l,column:b},b.id):e.jsx(el,{droppableId:t,sortableType:l,column:b},b.id)}const g=u?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(b=>b.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:d,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(b=>p(b))})]})})}function rl(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function ll(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(nl,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:n})})}function ol(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(La,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Dt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Is,{}),e.jsx(Es,{variant:"default"})]})]})}function il(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,u,d,m;r?((i=t.current)==null||i.resize(0),(u=n.current)==null||u.resize(0)):((d=t.current)==null||d.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Yr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Qe,{})})]}):e.jsx(Qe,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(Zr,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(ol,{}),e.jsx(ll,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Qe,{})})]})})]}):e.jsx(Qe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function cl(t){s.useAIInteractionStore(Y=>Y.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o}=s.useSemaphorContext(),c=s.useEditorStore(Y=>{var q;return(q=Y==null?void 0:Y.card)==null?void 0:q.sql}),i=s.useEditorStore(Y=>Y.isDevMode),u=s.useEditorStore(Y=>{var q;return(q=Y==null?void 0:Y.card)==null?void 0:q.python}),{setCardPython:d,setCardSql:m,setRunSql:h,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),j=s.useEditorStore(Y=>Y.currentAssitantScope)||[],x=s.useEditorStore(Y=>Y.userInputForAI),b=s.useEditorStore(Y=>Y.triggerAIRun),f=s.useEditorStore(Y=>Y.card),N=s.useEditorStore(Y=>Y.selectedDatabaseName),T=s.useEditorStore(Y=>Y.selectedTableName),I=s.useEditorStore(Y=>Y.selectedConnectionId),C=s.useEditorStore(Y=>Y.selectedSchemaName),S=s.useDashboardStore(Y=>Y.dashboard.aiScopeTables),{errorMessage:y,refetch:E,data:v}=s.useDashboardCardQuery(f),{setTriggerAIRun:O,setCurrentAssitantScope:k,setCardConfig:F}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:D,selectedDatamodelId:M}=s.useEditorAside(),{messages:R,setMessages:L,regenerate:B,error:z,sendMessage:$,status:_,addToolResult:Z,stop:se,clearError:W}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const Y=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:Y.currentAIContext,reasoningEffort:Y.reasoningEffort,showReasoning:Y.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:Y,body:q})=>({body:{...q,messages:s.cleanupIncompleteMessages(Y)}})}),onError:Y=>{console.log("on error",Y)},onToolCall:J,onFinish(){a("")}});A.useEffect(()=>{b&&x&&($({role:"user",parts:[{type:"text",text:x}]}),O(!1))},[b,x,$,O]);async function J({toolCall:Y}){var q,ae,oe,ie,ue,xe,pe,X,V,H,ee,ne,re,je,me,Ke;if(["createChartFromSql","createForecast"].includes(Y.toolName)){const Ge=((q=Y.input)==null?void 0:q.sql)??((ae=Y.args)==null?void 0:ae.sql),ke=((oe=Y.input)==null?void 0:oe.python)??((ie=Y.args)==null?void 0:ie.python),he=((ue=Y.input)==null?void 0:ue.chartType)??((xe=Y.args)==null?void 0:xe.chartType);p(he),m(Ge),d(ke),h(!0),Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(Y.toolName==="getUserSql"){if(!c){Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"error",message:"No SQL found"}});return}Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(Y.toolName==="generateQueryConfig"){a("Generating query config...");const Ge=((pe=Y.input)==null?void 0:pe.chartType)??((X=Y.args)==null?void 0:X.chartType),ke=((V=Y.input)==null?void 0:V.queryConfig)??((H=Y.args)==null?void 0:H.queryConfig);((ee=Y.input)==null?void 0:ee.cardConfig)??((ne=Y.args)==null||ne.cardConfig),p(Ge),F(ke),m(void 0),d(void 0);const he=await E();if((re=he==null?void 0:he.data)!=null&&re.error){Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"error",queryConfig:ke,message:(je=he==null?void 0:he.data)==null?void 0:je.error.message}});return}if((me=he==null?void 0:he.data)!=null&&me.records){Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"success",queryConfig:ke,message:"The data has been visualized"}});return}Z({tool:Y.toolName,toolCallId:Y.toolCallId,output:{status:"success",queryConfig:ke,message:"The data has been visualized",records:(Ke=he==null?void 0:he.data)==null?void 0:Ke.records}})}else a("Analyzing...")}function G(Y){const q=s.removeFromScopeArray(j,Y);Q(q)}function Q(Y){const q=s.sanitizeAIScope(Y);k(q),L(ae=>[...ae,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(q)}`}]}])}function P(){const Y={databaseName:N||"",schemaName:C||"",tableName:T||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||""},q=s.dedup([...j,Y]);Q(q)}function U(){const Y={databaseName:N||"",schemaName:C||"",tableName:T||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||"",datamodelId:M||""};if(!s.isInAiScopeArray([...S||[],...j],Y)||j.length===0){const ae=s.dedup([...S||[],...j,Y]).filter(oe=>oe.connectionId===Y.connectionId);Q(ae)}}const te=!["ready","error"].includes(_),le=s.getErrorMessage(z);return{messages:R,setMessages:L,sendMessage:$,regenerate:B,isLoading:te,handleSetAIScope:U,handleAddCurrentTableToScope:P,removeFromCurrentSelections:G,currentAssitantScope:j,setCurrentAssitantScope:k,stop:se,status:_,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:le,clearError:W}}const dl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Js(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,u]=A.useState(!1),d=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:p}=s.useFileActions(),g=s.useFileAttachments("editor"),j=s.useDashboardStore(H=>H.dashboard.aiContext),x=s.useEditorStore(H=>H.card.dataSource),b=s.useEditorStore(H=>H.actions.setCardSql),f=s.useEditorStore(H=>H.actions.setRunSql),N=s.useEditorStore(H=>H.showAIDialog),T=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:C}=s.useEditorActions(),{setDataSource:S}=s.useEditorActions(),{assistantProfile:y}=s.useAssistantProfile(),{messages:E,setMessages:v,sendMessage:O,isLoading:k,stop:F,status:w,llmUsage:D,errorMessage:M,clearError:R}=cl(),[L,B]=A.useState(""),z=H=>{B(H.target.value)},$=H=>{H.preventDefault();const ee=L.trim();if(!ee&&g.length===0)return;const ne=[];ee&&ne.push({type:"text",text:ee}),g.forEach(re=>{re.data&&ne.push({type:"file",mediaType:re.type,filename:re.name,url:`data:${re.type};base64,${re.data}`})}),O({role:"user",parts:ne}),B(""),p("editor"),te({force:!0})},{visibleMessages:_,hasMoreMessages:Z,totalMessageCount:se,loadMoreMessages:W,resetMessageWindow:J}=s.useMessageWindow(E,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:G,isAtBottom:Q,hasNewMessages:P,newMessageCount:U,scrollToBottom:te,handleScroll:le,resetNewMessageCount:Y}=s.useAutoScroll(_,{threshold:50,delay:0,dependencies:[w,E.length]});A.useEffect(()=>{var H;N&&((H=t.current)==null||H.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[N,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:w,isLoading:k,sendMessage:O});const{hasActiveTools:q}=s.useActiveToolStatus(E);function ae(H,ee){ee==="sql"?(b(H),f(!0)):ee==="python"&&(C(H),f(!0))}function oe(){var H;(H=j==null?void 0:j.selectedEntities)==null||H[0],u(!0)}function ie(){d.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function ue(H){ie();const ee={role:"user",parts:[{type:"text",text:H.title+" "+H.subtitle}]};O(ee)}function xe(H){ie(),O({role:"user",parts:[{type:"text",text:H}]})}function pe(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function X(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const V=(L==null?void 0:L.length)===0&&(E==null?void 0:E.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[X(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(y==null?void 0:y.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:oe,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{v([]),h("editor"),R(),J()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{I(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:G,className:"mt-2 flex w-full grow basis-0",onScroll:le,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Z&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:W,className:"text-xs",children:["Load ",Math.min(5,se-_.length)," more messages (",se-_.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:_,showTools:r,handleRun:ae,showSystemMessage:o}),!q&&e.jsx(s.AssistantStatus,{status:w,errorMessage:M})]})}),!Q&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{te({force:!0}),Y()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),P&&U>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[V&&!y&&e.jsx(s.Placeholders,{onClick:ue,placeholders:dl}),e.jsx("div",{children:V&&y&&e.jsx(s.SeedQuestions,{seedQuestions:y.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:B,stop:F,input:L,handleInputChange:z,handleSubmit:H=>{ie(),$(H),te({force:!0})},isLoading:k,status:w,assistantType:"editor",onFocus:()=>{}})]}),D&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",D.inputTokens," prompt tokens, ",D.outputTokens," ","completion tokens, ",D.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:u,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Rs=t=>{var k;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:u,removeSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(F=>F.card.type),h=t==null?void 0:t.id,p=A.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){case"groupBy":return(t.config.groupByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,dateFormat:w.dateFormat,customFormat:w.customFormat,granularity:w.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,direction:w.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((F,w)=>{if(h)switch(F){case"groupBy":{n(h,{groupByColumns:w});break}case"metrics":{n(h,{metricColumns:w});break}case"pivotBy":{n(h,{pivotByColumns:w});break}case"sortBy":{n(h,{sortByColumns:w});break}}},[h,n]),j=A.useCallback((F,w,D)=>{if(!h)return;const R=p(F)[w];if(R)switch(F){case"groupBy":a(h,R.id,{label:D});break;case"metrics":r(h,R.id,{label:D});break;case"pivotBy":l(h,R.id,{label:D});break;case"sortBy":o(h,R.id,{label:D});break}},[h,p,a,r,l,o]),x=A.useCallback((F,w)=>{if(!h)return;const M=p("metrics")[F];M&&r(h,M.id,{aggregate:w,label:s.getAggregationLabel(M.name,w)})},[h,p,r]),b=A.useCallback((F,w,D)=>{if(!h)return;const R=p("groupBy")[F];if(!R)return;const L={dateFormat:w};w==="custom"&&D?L.customFormat=D:L.customFormat=void 0,a(h,R.id,L)},[h,p,a]),f=A.useCallback((F,w)=>{if(!h)return;const M=p("groupBy")[F];M&&a(h,M.id,{granularity:w})},[h,p,a]),N=A.useCallback((F,w)=>{if(!h)return;const M=p("metrics")[F];M&&r(h,M.id,{aliasTemplate:w})},[h,p,r]),T=A.useCallback((F,w)=>{if(console.log("handleValueAliasesChange",F,w),!h)return;console.log("handleValueAliasesChange",F,w);const M=p("metrics")[F];M&&(console.log("handleValueAliasesChange",w),r(h,M.id,{valueAliases:w}))},[h,p,r]),I=A.useCallback(F=>{h&&n(h,{comparisonType:F})},[h,n]),C=A.useCallback(F=>{h&&n(h,{showTrendline:F})},[h,n]),S=A.useCallback(F=>{h&&n(h,{trendlineWindow:F})},[h,n]),y=A.useCallback(F=>{h&&n(h,{trendlineGranularity:F})},[h,n]),E=A.useCallback(F=>{h&&n(h,{targetValue:F})},[h,n]),v=A.useCallback(F=>{var z;if(!h)return;const w=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],D=(z=t==null?void 0:t.config)==null?void 0:z.joinPlan,M=s.validateEntityConsistency(F,w,D);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const R=s.getSmartContainerForField(F,w),L=p(R);if(s.fieldAlreadyExists(F,L))return;const B=s.getNewField(F,R,L);B&&g(R,[...L,B])},[h,(k=t==null?void 0:t.config)==null?void 0:k.joinPlan,p,g]),O=A.useCallback((F,w)=>{if(!h)return;const M=p(F)[w];if(M){if(F!=="sortBy"){const R=p("sortBy"),L=R.filter(B=>!(B.name===M.name&&B.qualifiedEntityName===M.qualifiedEntityName));L.length!==R.length&&n(h,{sortByColumns:L})}switch(F){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":u(h,M.id);break;case"sortBy":d(h,M.id);break}}},[h,p,c,i,u,d,n]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:O,handleFieldClick:v,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:E,cardType:m}};function ul({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function ml({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,u]=A.useState(!1),d=s.useEditorStore(j=>j.card),{handleFieldClick:m}=Rs(d),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return De;case"date":return s.Calendar;case"boolean":return Le;case"json":return Pe;case"geo":return $e;default:return ye}},g=j=>{const x=(j||"").toLowerCase(),b=s.getDataType(x);return b==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):b==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):b==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):b==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):b==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):b==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):b==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(We,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ul,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function hl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(T=>T.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:u}=s.useColumns(),d=o.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=T=>{if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=s.getDataType(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},p=(a==="all"?d:d.filter(T=>m(T)===a)).reduce((T,I)=>{const C=I.qualifiedEntityName||"Other Fields";return T[C]||(T[C]={label:s.toLabel(I.entityName),fields:[]}),T[C].fields.push(I),T},{}),j=Object.keys(p),x=d.filter(T=>m(T)==="dimensions").length,b=d.filter(T=>m(T)==="metrics").length,f=d.filter(T=>m(T)==="calculated").length,N=d.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):u?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:T=>r(T),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:d.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(We,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(p).map(([T,I])=>{const C=c.find(S=>S.entityName===T)||{entityName:T,label:I.label};return e.jsxs(s.AccordionItem,{value:T,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:C.label||C.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:C.label||C.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:I.fields.map(S=>e.jsx(ml,{field:S},S.id))})})]},T)})}),Object.keys(p).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function xl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(hl,{})," "]})}function pl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(E=>E.sequence))+1:1,y={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,y]}),o(new Set([...l,y.id]))},i=S=>{r({...a,joins:a.joins.filter(y=>y.id!==S)}),o(new Set([...l].filter(y=>y!==S)))},u=(S,y)=>{var k,F;const E=a.joins.find(w=>w.id===S);if(!E)return;const v={...E,...y},O=a.joins.map(w=>w.id===S?v:w);if((k=v.source)!=null&&k.name&&((F=v.target)!=null&&F.name)&&v.joinKeyGroups[0].keys.length===0){const w=n.find(L=>{var B;return L.name===((B=v.source)==null?void 0:B.name)}),D=n.find(L=>{var B;return L.name===((B=v.target)==null?void 0:B.name)}),M={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:"="},R=[...v.joinKeyGroups];R[0]={...R[0],keys:[M]},v.joinKeyGroups=R,O[O.findIndex(L=>L.id===S)]=v}r({...a,joins:O})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:u,moveJoinUp:S=>{const y=a.joins.findIndex(E=>E.id===S);if(y>0){const E=[...a.joins],v={...E[y]},O={...E[y-1]};E[y]=O,E[y-1]=v,E.forEach((F,w)=>{F.sequence=w+1});const k={...a,joins:E};r(k)}},moveJoinDown:S=>{const y=a.joins.findIndex(E=>E.id===S);if(y<a.joins.length-1){const E=[...a.joins],v={...E[y]},O={...E[y+1]};E[y]=O,E[y+1]=v,E.forEach((F,w)=>{F.sequence=w+1});const k={...a,joins:E};r(k)}},toggleJoinExpansion:S=>{const y=new Set(l);y.has(S)?y.delete(S):y.add(S),o(y)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const y=a.joins.findIndex(v=>v.id===S);if(y===0)return n;const E=new Set;return a.baseEntity.name&&E.add(a.baseEntity.name),a.joins.slice(0,y).forEach(v=>{E.add(v.source.name),E.add(v.target.name)}),n.filter(v=>E.has(v.name))},getAvailableTargetEntities:S=>n.filter(y=>y.name!==S),addJoinKeyGroup:S=>{const y=a.joins.find(v=>v.id===S);if(!y)return;const E=[...y.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];u(S,{joinKeyGroups:E})},updateGroupOperator:(S,y,E)=>{const v=a.joins.find(k=>k.id===S);if(!v)return;const O=[...v.joinKeyGroups];O[y]={...O[y],operator:E},u(S,{joinKeyGroups:O})},removeJoinKeyGroup:(S,y)=>{const E=a.joins.find(O=>O.id===S);if(!E)return;const v=[...E.joinKeyGroups];v.splice(y,1),u(S,{joinKeyGroups:v})},addJoinKey:(S,y)=>{const E=a.joins.find(w=>w.id===S);if(!E)return;const v=n.find(w=>w.name===E.source.name),O=n.find(w=>w.name===E.target.name),k=[...E.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};k[y]={...k[y],keys:[...k[y].keys,F]},u(S,{joinKeyGroups:k})},updateJoinKey:(S,y,E,v,O)=>{const k=a.joins.find(R=>R.id===S);if(!k)return;const F=n.find(R=>R.name===k.source.name),w=n.find(R=>R.name===k.target.name),D=[...k.joinKeyGroups],M=D[y].keys[E];v==="sourceColumnName"&&F?D[y].keys[E]={...M,source:{...M.source,name:O}}:v==="targetColumnName"&&w?D[y].keys[E]={...M,target:{...M.target,name:O}}:v==="operator"&&(D[y].keys[E]={...M,operator:O}),u(S,{joinKeyGroups:D})},removeJoinKey:(S,y,E)=>{const v=a.joins.find(k=>k.id===S);if(!v)return;const O=[...v.joinKeyGroups];O[y].keys.splice(E,1),u(S,{joinKeyGroups:O})},generateSQLPreview:()=>{const S=[...a.joins].sort((v,O)=>v.sequence-O.sequence),y=a.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
359
- FROM ${y.name}`;return S.forEach(v=>{const O=n.find(w=>w.name===v.target.name);if(!O)return;const k=v.joinKeyGroups.filter(w=>w.keys&&w.keys.length>0).map(w=>{const D=w.keys.filter(M=>{var R,L,B,z;return((R=M.source)==null?void 0:R.name)&&((L=M.target)==null?void 0:L.name)&&((B=M.source)==null?void 0:B.entityName)&&((z=M.target)==null?void 0:z.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return D.length>1?`(${D.join(` ${w.operator} `)})`:D[0]}).filter(Boolean),F=k.length>1?k.join(" OR "):k[0]||"condition_here";E+=`
360
- ${v.joinType} JOIN ${O.name}
361
- ON ${F}`}),E},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(v=>!v.source.name||!v.target.name)||a.joins.some(v=>v.joinKeyGroups.some(O=>O.keys.length===0))||a.joins.some(v=>v.joinKeyGroups.some(O=>O.keys.some(k=>!k.source.name||!k.target.name||!k.operator))))}}function fl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:u,setJoinPlan:d,addJoin:m,removeJoin:h,updateJoin:p,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:b,getAvailableTargetEntities:f,addJoinKeyGroup:N,updateGroupOperator:T,removeJoinKeyGroup:I,addJoinKey:C,updateJoinKey:S,removeJoinKey:y,generateSQLPreview:E,isValidConfiguration:v}=pl({initialJoinPlan:t,availableDataSources:n}),O=k=>{const F=c.find(w=>w.entityName===k);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:k=>{const F=n.find(w=>w.name===k);d({...i,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:k,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:E()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(k=>{const F=n.find(M=>M.name===k.source.name),w=n.find(M=>M.name===k.target.name),D=u.has(k.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,F&&w&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",w.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(k.id),disabled:k.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(k.id),children:D?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),D&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:k.source.name,onValueChange:M=>{const R=n.find(L=>L.name===M);p(k.id,{source:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:M,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:b(k.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:M=>p(k.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:k.target.name,onValueChange:M=>{const R=n.find(L=>L.name===M);p(k.id,{target:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:M,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?f(k.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),k.source.name&&k.target.name&&F&&w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>N(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((M,R)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",R+1]}),R>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:L=>T(k.id,R,L),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(k.id,R),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((L,B)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[B>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.source.name,onValueChange:z=>S(k.id,R,B,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:O(k.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:L.operator,onValueChange:z=>S(k.id,R,B,"operator",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.target.name,onValueChange:z=>S(k.id,R,B,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:O(k.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(k.id,R,B),children:e.jsx(s.X,{className:"size-3.5"})})]},L.id||B))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(k.id,R),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!v(),children:"Save"})]})]})}function Qs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(fl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function gl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(u=>u.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(u=>u.name===l.source.name),i=a.find(u=>u.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((u,d)=>u+d.keys.length,0)," ","condition",l.joinKeyGroups.reduce((u,d)=>u+d.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function jl(){var m,h;const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{l(!1)},d=()=>{const p=[...a.joins].sort((x,b)=>x.sequence-b.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
362
- FROM ${g.name}`;return p.forEach(x=>{const b=o.find(T=>T.name===x.target.name);if(!b)return;const f=x.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const I=T.keys.filter(C=>{var S,y,E,v;return((S=C.source)==null?void 0:S.name)&&((y=C.target)==null?void 0:y.name)&&((E=C.source)==null?void 0:E.entityName)&&((v=C.target)==null?void 0:v.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return I.length>1?`(${I.join(` ${T.operator} `)})`:I[0]}).filter(Boolean),N=f.length>1?f.join(" OR "):f[0]||"condition_here";j+=`
363
- ${x.joinType} JOIN ${b.name}
364
- ON ${N}`}),j};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(gl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:d})})]})}),e.jsx(Qs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Qs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function bl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(b=>b.some(N=>N.name===x.name&&N.type===x.type)?b.filter(N=>!(N.name===x.name&&N.type===x.type)):[...b,x])},u=()=>{r([...c])},d=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],b=x.connectionId||"",f=x.connectionType||"",T=a.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:b,connectionType:f,mode:T,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ja,{className:"h-4 w-4"});case"model":return e.jsx(ga,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},p=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const b=[];return x.database&&b.push(x.database),x.schema&&b.push(x.schema),x.name&&b.push(x.name),b.join(".")},j=x=>a.some(b=>b.name===x.name&&b.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,b)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${b}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function yl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},u))})]})})}function vl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Nl({isVisible:t,onToggleVisibility:n}){const[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(p=>p.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...u,selectedEntities:(u==null?void 0:u.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:n,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((p,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(p),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(b=>!(b.name===p.name&&b.type===p.type));d({...m,...u,selectedEntities:x})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(yl,{entity:p})]},`${p.type}-${p.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(vl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(jl,{})]})]}),e.jsx(xl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(bl,{open:l,onOpenChange:o})]})}const Cl="chart-selector-standard-first";function Sl(){const[t,n]=s.useLocalStorageState(Cl,!0);return{standardFirst:t,updatePreference:n}}const Xs=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Zs=["default","standardPlugin","customPlugin"];function wl({selectedChart:t,onChartChange:n}){var I;const[a,r]=A.useState(!1),{data:l}=It();Sl();const c=((I=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:I.url)||"";Ds(c);const{setCardType:i,setCardPreferences:u,setIsDevMode:d}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...Zs.filter(C=>C!==g)]:Zs,[g]);function b(C){m(null),u({}),i(C),["custom","map"].includes(C)&&(d(!0),p(void 0)),n(C),r(!1)}function f(C){m(null),u({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),p(void 0),n("custom"),r(!1)}const N=()=>{var S;if(t==="custom"){const y=s.useEditorStore.getState().card;return((S=y==null?void 0:y.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const C=s.chartTypes.find(y=>y.id===t);return(C==null?void 0:C.label)||"Select chart type"},T=()=>{var S,y;if(t==="custom"){const E=s.useEditorStore.getState().card,v=(S=E==null?void 0:E.customCardPreferences)==null?void 0:S.icon,O=(y=E==null?void 0:E.customCardPreferences)==null?void 0:y.componentName;if(v&&O)return e.jsx(Dl,{icon:v,componentName:O});if(O){const k=s.getAutoDetectedChartIcon(O);if(k)return k}return e.jsx(qe,{className:"h-4 w-4"})}const C=s.chartTypes.find(E=>E.id===t);if(C){const E=C.icon;return e.jsx(E,{className:"h-4 w-4"})}return e.jsx(qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:N()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),x.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:S=>j(S?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(S=>{const y=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>b(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(C==="standardPlugin"){const S=l.filter(y=>y.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:y=>j(y?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(y=>y.componentType==="chart").map((y,E)=>e.jsx(Xs,{pluginVisual:y,index:E,onSelect:()=>f(y)},`${y.url}-${y.name}-${E}`))},"standardPlugin"):null}if(C==="customPlugin"){const S=l.filter(y=>y.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:y=>j(y?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((y,E)=>e.jsx(Xs,{pluginVisual:y,index:E,onSelect:()=>f(y)},`${y.url}-${y.name}-${E}`))},"customPlugin"):null}return null})]})]})})]})})}const Dl=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},kl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function Tl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:kl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Os=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})};function El({aliasTemplate:t,onAliasTemplateChange:n}){var u;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(u=s.useEditorStore(d=>{var m;return(m=d.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:d=>{r(d.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:d=>d.stopPropagation(),className:"h-8 text-xs",onKeyDown:d=>{d.key==="Enter"&&l&&a!==t?(n(a),o(!1)):d.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Il({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),u=()=>{n({...t,"":""})},d=h=>{const p={...t};delete p[h],n(p)},m=h=>{const p={...t};delete p[h],p[l]=c,n(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Al({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},d={connection_id:o.connectionId,cardConfig:u,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",d);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",d);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Ml({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var T,I;const c=!!l,[i,u]=A.useState(c?"values":"fields"),[d,m]=A.useState(""),[h,p]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(C=>{var y;return c?!1:!((y=r==null?void 0:r.conditions)==null?void 0:y.some(E=>E.field.id===C.id))&&C.label.toLowerCase().includes(d.toLowerCase())}),j=C=>{p({...h,field:C}),u("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const y=((r==null?void 0:r.conditions)||[]).map(E=>E.id===l.id?C:E);S={...r,conditions:y}}else{const y=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...y,C],groups:[]}}o(S),n(!1)}},b=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(C.length>0){const S={...r,conditions:C};o(S)}else o(void 0);n(!1)},f=C=>{p({...h,selectedValues:C})},N=()=>{c&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),u("values")):(p({id:s.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return A.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(T=h.field)==null?void 0:T.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(I=h.field)==null?void 0:I.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>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:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:d,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(C),children:[e.jsx(Os,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&d&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',d,'"']}),g.length===0&&!d&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ll,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,onBack:c?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:N,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ll({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:u}=Al({field:t,searchQuery:l,limit:500}),d=l?c.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):c,m=p=>{const g=n.includes(p);a(g?n.filter(j=>j!==p):[...n,p])},h=()=>{n.length===d.length&&d.length>0?a([]):a(d.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:p=>o(p.target.value),className:"pl-10"})]}),i||u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===d.length&&d.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",d.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:d.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>m(p.value)}),e.jsx(cs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Rl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Ps,zs,_s;const{attributes:i,listeners:u,setNodeRef:d,transform:m,transition:h,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(K=>K.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:I,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:v}=Rs(g),[O,k]=A.useState(!1),[F,w]=A.useState(!1),[D,M]=A.useState(null),[R,L]=A.useState(t.dateFormat||"YYYY-MM-DD"),[B,z]=A.useState(t.customFormat||""),[$,_]=A.useState(!!t.customFormat),[Z,se]=A.useState(t.granularity||"day"),[W,J]=A.useState(t.aliasTemplate||""),[G,Q]=A.useState(t.valueAliases||{}),[P,U]=A.useState((Ps=t.parameters)==null?void 0:Ps.filters),te=K=>{K==="custom"?_(!0):(_(!1),L(K),n==="groupBy"&&b(a,K,""))},le=K=>{z(K),n==="groupBy"&&b(a,"custom",K)},Y=K=>{var fe;se(K);const de=(fe=H(K)[0])==null?void 0:fe.value;de&&!$&&(L(de),n==="groupBy"&&b(a,de,"")),n==="groupBy"&&f(a,K)},q=K=>{J(K),n==="metrics"&&N(a,K)},ae=K=>{Q(K),n==="metrics"&&T(a,K)},oe=K=>{j(n,a,K)},ie=K=>{var ce;if(U(K),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:K}},fe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];fe[a]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:fe})}w(!1)},ue=()=>{I(n,a)},xe={transform:s.CSS.Transform.toString(m),transition:h},pe=s.getDataType(t.dataType),X=pe==="date",V=c==="kpi",H=K=>{switch(K){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ee=H(Z),ne=n!=="pivotBy",re=X&&n==="groupBy",je=!V&&X&&n==="groupBy",me=V&&X&&n==="groupBy",Ke=V&&n==="metrics"&&((zs=g.config)==null?void 0:zs.comparisonType)==="target",Ge=n==="metrics",ke=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),he=()=>ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:oe,placeholder:"Display label...",type:"text"})]}):null,Fs=()=>re?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:Z,onValueChange:Y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,Kt=()=>je?e.jsxs(e.Fragment,{children:[Fs(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:$?"custom":R,onValueChange:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ee.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),$&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:B,onChange:K=>{K.stopPropagation(),le(K.target.value)},onClick:K=>K.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,Jt=()=>{var K,ce,de,fe,Te;return me?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((K=g.config)==null?void 0:K.comparisonType)||"none",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ce=g.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:S})]})}),((de=g.config)==null?void 0:de.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((fe=g.config)==null?void 0:fe.trendlineWindow)||30,onChange:Je=>{const sa=parseInt(Je.target.value)||30;y(sa)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((Te=g.config)==null?void 0:Te.trendlineGranularity)||"day",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Qt=()=>{var K,ce;return Ke?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(we,{value:((K=g.config)==null?void 0:K.targetValue)!==void 0&&((ce=g.config)==null?void 0:ce.targetValue)!==null?String(g.config.targetValue):"",onSave:de=>{!isNaN(Number(de))&&de!==null?v(Number(de)):v(0)},placeholder:"Enter target value...",type:"text"})]}):null},Xt=()=>Ge?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:K=>{x(a,K)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(P==null?void 0:P.conditions)&&P.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:P.conditions.map(K=>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:()=>{M(K),w(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((ce,de)=>e.jsx("div",{children:String(ce)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var fe;ce.stopPropagation();const de=P.conditions.filter(Te=>Te.id!==K.id);if(de.length>0){const Te={...P,conditions:de};ie(Te)}else if(U(void 0),n==="metrics"){const Te={...t,parameters:{...t.parameters,filters:void 0}},Je=[...((fe=g.config)==null?void 0:fe.metricColumns)||[]];Je[a]=Te,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Je})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),w(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx($t,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(El,{aliasTemplate:W,onAliasTemplateChange:q}),e.jsx(Il,{valueAliases:G,onValueAliasesChange:ae})]})]}):null,{columns:Zt=[]}=s.useColumns(),ea=(P==null?void 0:P.conditions)&&P.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:d,style:xe,...i,...u,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Os,{dataType:pe}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-sm",ea&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((_s=P==null?void 0:P.conditions)==null?void 0:_s.length)&&!O&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:P.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:P.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:K=>{K.stopPropagation(),k(!O)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${O?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ce=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ce),l(ce)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:K=>{K.stopPropagation(),ue()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[ke(),he(),c==="kpi"&&Fs(),Kt(),Jt(),Qt(),Xt()]})]}),F&&e.jsx(Ml,{open:F,onOpenChange:K=>{w(K),K||M(null)},availableFields:Zt,existingFilters:P,editingCondition:D,onSave:K=>{var ce;if(K)ie(K);else if(U(void 0),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:void 0}},fe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];fe[a]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:fe})}M(null)}})]})}function Ol({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Ze({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),d=s.useEditorStore(j=>j.card),m=s.useEditorStore(j=>j.card.type),h=n.length>0,p=(j,x)=>{var f;!((f=d.config)!=null&&f.sortByColumns)||d.config.sortByColumns.findIndex(N=>N.id===j)===-1||u(d.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Ol,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,x)=>{const f=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Rl,{field:j,zone:t,index:x,sortDirection:f,onSortDirectionChange:N=>p(j.id,N),hasPivotColumns:o,cardType:m})})},j.id)})})})})]})}const et=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Bl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const u=et.find(d=>d.value===t);return u?u.color:t.startsWith("#")?t:et[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Bl.map(u=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===u?"border-gray-900":"border-transparent"),style:{backgroundColor:u},onClick:()=>{n(u),l(!1)},children:e.jsx("span",{className:"sr-only",children:u})},u))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&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:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(zt,{color:i(),onColorChange:u=>{n(u),c(!1)},onClose:()=>c(!1)})})]})]})}const es={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
365
- Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Fl(){var i,u,d,m,h,p,g,j,x,b;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((u=t.config)==null?void 0:u.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...f}}};n(N)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(es).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,T,I;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=es[f])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=es[f])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(I=es[f])==null?void 0:I.example]})]})})()]}),e.jsx(Ms,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:f=>c({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(js,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((p=o.colorConfig)==null?void 0:p.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((x=o.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.noChange)??"No change",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Pl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var u;const i={...t.preferences,kpiVisualOptions:{...(u=t.preferences)==null?void 0:u.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ms,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function zl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(j=>{var x;return((x=j.card.customCardPreferences)==null?void 0:x.url)&&j.card.type==="custom"}),o=s.useEditorStore(j=>j.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,u=c!=="kpi",d=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=u&&!m,p=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Ze,{zone:"groupBy",fields:t,label:p().label,placeholder:p().placeholder}),h&&e.jsx(Ze,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),d&&e.jsx(Ze,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Pl,{}),e.jsx(Fl,{}),e.jsx(_t,{}),e.jsx(Vt,{}),e.jsx(Ut,{}),e.jsx(Gt,{})]})})]})]})}function _l({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:u}=s.useEditorActions(),d=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(d);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(wl,{selectedChart:t,onChartChange:n}),e.jsx(Tl,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(os,{})}),!c&&e.jsxs(s.Button,{onClick:()=>u(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(zl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Vl({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],u={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},d=C=>{const S=y=>{if(y.id===C){const E=i[0]||u,v=s.getDataType(E.dataType)==="date";return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:E,operator:v?"between":"=",value:v?[]:""}]}}return{...y,groups:y.groups.map(S)}};r(S(a))},m=C=>{const S=y=>{if(y.id===C){const E=i[0]||u,v=s.getDataType(E.dataType)==="date";return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:v?"between":"=",value:v?[]:""}],groups:[]}]}}return{...y,groups:y.groups.map(S)}};r(S(a))},h=(C,S)=>{const y=E=>E.id===C?{...E,conditions:E.conditions.filter(v=>v.id!==S)}:{...E,groups:E.groups.map(y)};r(y(a))},p=(C,S)=>{const y=E=>E.id===C?{...E,groups:E.groups.filter(v=>v.id!==S)}:{...E,groups:E.groups.map(y)};r(y(a))},g=(C,S,y,E)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const v=O=>O.id===C?{...O,conditions:O.conditions.map(k=>k.id===S?{...k,[y]:E}:k)}:{...O,groups:O.groups.map(v)};r(v(a))},j=(C,S,y)=>{const E=v=>v.id===C?{...v,conditions:v.conditions.map(O=>O.id===S?{...O,...y}:O)}:{...v,groups:v.groups.map(E)};r(E(a))},x=(C,S)=>{const y=E=>E.id===C?{...E,logicalOperator:S}:{...E,groups:E.groups.map(y)};r(y(a))},b=(C,S)=>{const y=E=>E.id===C?{...E,negate:S}:{...E,groups:E.groups.map(y)};r(y(a))},f=(C,S,y)=>{const E=v=>v.id===C?{...v,conditions:s.arrayMove(v.conditions,S,y)}:{...v,groups:v.groups.map(E)};r(E(a))},N=(C,S,y)=>{const E=v=>v.id===C?{...v,groups:s.arrayMove(v.groups,S,y)}:{...v,groups:v.groups.map(E)};r(E(a))},T=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const S=E=>{let v="";typeof E.field=="object"?v=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:v=String(E.field);const O=E.operator;let k=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof k=="string"?k=`'${k}'`:Array.isArray(k)&&(k=`'${k.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(k)&&k.length===2){const F=k[0]?`'${k[0]}'`:"NULL",w=k[1]?`'${k[1]}'`:"NULL";return`${v} BETWEEN ${F} AND ${w}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(k)){const F=k.map(w=>w?`'${w}'`:"NULL").join(", ");return`${v} ${O} (${F})`}else typeof k=="string"||k instanceof Date?k=`'${k}'`:Array.isArray(k)&&k.length>0&&(k=`'${k[0]}'`);else if(["in","not in"].includes(E.operator)){let F=[];Array.isArray(k)?F=k.map(w=>typeof w=="string"?`'${w}'`:String(w)):typeof k=="string"?F=k.split(",").map(w=>{const D=w.trim();return E.field.dataType==="string"?`'${D}'`:D}):typeof k=="number"&&(F=[String(k)]),k=`(${F.join(", ")})`}switch(O){case"contains":return typeof k=="string"?`${v} LIKE '%${k.replace(/'/g,"")}'`:`${v} LIKE '%${String(k)}'`;case"startsWith":return typeof k=="string"?`${v} LIKE '${k.replace(/'/g,"")}%'`:`${v} LIKE '${String(k)}%'`;case"endsWith":return typeof k=="string"?`${v} LIKE '%${k.replace(/'/g,"")}'`:`${v} LIKE '%${String(k)}'`;case"isNull":return`${v} IS NULL`;case"isNotNull":return`${v} IS NOT NULL`;default:return`${v} ${O} ${k}`}},y=E=>{const v=E.conditions.map(S),O=E.groups.map(D=>y(D)),k=[...v,...O].filter(Boolean);if(k.length===0)return"";const F=k.join(` ${E.logicalOperator} `),w=k.length>1?`(${F})`:F;return E.negate?`NOT ${w}`:w};return y(C)},I=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:d,addGroup:m,removeCondition:h,removeGroup:p,updateCondition:g,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:b,reorderConditions:f,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:I}}function Ul({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Gl=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Yl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function $l({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const u={};return a.forEach(d=>{const m=Yl(d);u[m]||(u[m]={}),u[m][d.entityId]||(u[m][d.entityId]=[]),u[m][d.entityId].push(d)}),u},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ul,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([u,d])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(d).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Gl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${u}-${m}`))},u))})]})})]})}function Bs(t){var j;const n=s.useEditorStore(x=>x.card),{authToken:a}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},u={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},d=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:m,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(a==null?void 0:a.accessToken)||"",{connection_id:d,cardConfig:u,cardDataSource:n.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!d,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x.value||"BLANK",value:x.value||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function ql({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ee.useState(!1),{filterValues:i}=Bs(t),u=m=>{a(n.filter(h=>h!==m))},d=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(p=>p.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&u(m)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),u(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>d(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.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+h))})]})]})})]})})}function Hl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Bs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((u,d)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+d))})]})}function Wl({value:t,operator:n,onChange:a,className:r}){var u;const{tokenProps:l}=s.useSemaphorContext(),o=(u=l==null?void 0:l.params)==null?void 0:u.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const d=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(d&&m)return{from:d,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:d}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:void 0,to:d}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const d=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):d;if(!isNaN(d.getTime()))return{from:d,to:m}}}},[t,n]),i=d=>{if(!d){a(void 0);return}if(d.from&&d.to)a([d.from.toISOString(),d.to.toISOString()]);else if(d.from){const m=new Date(d.from);m.setHours(23,59,59,999),a([d.from.toISOString(),m.toISOString()])}else if(d.to){const m=new Date(d.to);m.setHours(0,0,0,0),a([m.toISOString(),d.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Kl=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Jl=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ql=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Xl=["=","!=","isNull","isNotNull"],Zl=["between","isNull","isNotNull"],eo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function st(t){return eo[t]||s.titleCase(t)}function so(t){switch(t){case"string":return Jl;case"number":return Ql;case"boolean":return Xl;case"date":return Zl;default:return Kl}}function Ht({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:u}){const{attributes:d,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:b}=Bs(t.field),f={transform:s.CSS.Transform.toString(p),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...d,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx($l,{value:t.field,onValueChange:N=>{const T=N,I=s.getDataType(T.dataType)==="date";u(a,t.id,{field:T,value:"",operator:I?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?u(a,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?u(a,t.id,{operator:N,value:null}):u(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?st(t.operator):""})}),e.jsx(s.SelectContent,{children:so(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:st(N)},N))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ql,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>u(a,t.id,{value:N}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:N=>u(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Hl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>u(a,t.id,{value:N}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:N=>u(a,t.id,{value:N==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Wl,{value:t.value,operator:t.operator,onChange:N=>u(a,t.id,{value:N}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(a,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function to({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onReorderConditions:d,onReorderGroups:m,onAddCondition:h,onAddGroup:p,availableFields:g,renderFilterGroup:j,updateConditionFields:x}){const{attributes:b,listeners:f,setNodeRef:N,transform:T,transition:I,isDragging:C}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(T),transition:I},y=v=>{const{active:O,over:k}=v;if(k&&O.id!==k.id){const F=t.conditions.findIndex(D=>D.id===O.id),w=t.conditions.findIndex(D=>D.id===k.id);F!==-1&&w!==-1&&d(t.id,F,w)}},E=v=>{const{active:O,over:k}=v;if(k&&O.id!==k.id&&a){const F=t.groups.findIndex(D=>D.id===O.id),w=t.groups.findIndex(D=>D.id===k.id);F!==-1&&w!==-1&&m(a,F,w)}};return e.jsxs("div",{ref:N,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:v=>r(t.id,v),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.conditions.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((v,O)=>e.jsx(Ht,{condition:v,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},v.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(v=>j(v,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ao({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:u,addGroup:d,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:b,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:I}=Vl({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,y]=A.useState(!1),E=(k,F,w)=>{const D=M=>M.id===k?{...M,conditions:M.conditions.map(R=>R.id===F?{...R,field:w,dataType:w.dataType}:R)}:{...M,groups:M.groups.map(D)};I(D(o))},v=(k,F=0,w)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:M,over:R}=D;if(R&&M.id!==R.id){const L=k.conditions.findIndex(z=>z.id===M.id),B=k.conditions.findIndex(z=>z.id===R.id);L!==-1&&B!==-1&&b(k.id,L,B)}},children:e.jsx(s.SortableContext,{items:k.conditions.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:k.conditions.map((D,M)=>e.jsx(Ht,{condition:D,index:M,groupId:k.id,groupLogicalOperator:k.logicalOperator,onUpdateCondition:p,onUpdateField:E,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},D.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:M,over:R}=D;if(R&&M.id!==R.id){const L=k.groups.findIndex(z=>z.id===M.id),B=k.groups.findIndex(z=>z.id===R.id);L!==-1&&B!==-1&&f(k.id,L,B)}},children:e.jsx(s.SortableContext,{items:k.groups.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:k.groups.map(D=>v(D,F+1,k.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>u(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},k.id):e.jsx(to,{group:k,depth:F,parentGroupId:w,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:E,onRemoveCondition:m,onReorderConditions:b,onReorderGroups:f,onAddCondition:u,onAddGroup:d,availableFields:c,renderFilterGroup:v,updateConditionFields:g},k.id),O=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?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..."})]}):v(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:k=>y(!!k)}),e.jsx("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)"})]})}),T&&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:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function no({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=d=>{a(t,d),c(!1)},u=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:d=>{d.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ao,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:u})]})]})}function ro({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(j=>j.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],d=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(x=>x.id===j)?"source":a("groupBy").find(x=>x.id===j)?"groupBy":a("metrics").find(x=>x.id===j)?"metrics":a("pivotBy").find(x=>x.id===j)?"pivotBy":a("sortBy").find(x=>x.id===j)?"sortBy":null,[n,a]),m=A.useCallback(j=>{o(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:b}=j;if(!b||!t){o(null);return}const f=x.id,N=b.id,T=d(f),I=d(N)||N;if(I==="sortBy"){if(T==="source"){const C=n.find(y=>y.id===f);if(!C){o(null);return}if(!(a("groupBy").some(y=>y.name===C.name&&y.qualifiedEntityName===C.qualifiedEntityName)||a("metrics").some(y=>y.name===C.name&&y.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&I==="sortBy"){const C=[...n].find(E=>E.id===f);if(!C){o(null);return}const S=a("sortBy");if(s.fieldAlreadyExists(C,S)){o(null);return}const y=s.getNewField(C,"sortBy",S);o(null),r("sortBy",[...S,y]);return}if(T==="source"&&I!=="source"&&I!=="sortBy"){const C=[...n].find(v=>v.id===f);if(!C){o(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const v=S[0].qualifiedEntityName;if(!v){o(null);return}if(v!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(v,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const y=a(I);if(s.fieldAlreadyExists(C,y)){o(null);return}const E=s.getNewField(C,I,y);o(null),r(I,[...y,E]);return}if(T&&I&&T!=="source"&&I!=="source"&&T!==I){const C=a(T),S=a(I),y=C.find(O=>O.id===f);if(!y){o(null);return}const E=s.getNewField(y,I,S);if(o(null),I==="sortBy"){s.fieldAlreadyExists(y,S)||r(I,[...S,E]);return}const v=C.filter(O=>O.id!==f);r(T,v),r(I,[...S,E]);return}if(T&&I&&T===I&&T!=="source"){const C=a(T),S=C.findIndex(E=>E.id===f),y=C.findIndex(E=>E.id===N);if(S!==y){const E=s.arrayMove(C,S,y);r(T,E)}}o(null)},[t,n,a,r,d,i]),p=l?u.find(j=>j.id===l):null;return{activeId:l,activeField:p,handleDragStart:m,handleDragEnd:h}}function lo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,u=t>0,d=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),p=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:p}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):p}function oo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(f=>f.isDevMode),i=s.useEditorStore(f=>f.card),u=s.useEditorStore(f=>f.card.dataSource);s.isExplorerCard(i);const{config:d}=A.useContext(s.SemaphorContext).tokenProps,m=(d==null?void 0:d.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),j=s.useManagementStore(f=>f.selectedVisual),x=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:b}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!m&&"justify-end"),children:[m&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Is,{}),a&&!x&&e.jsx(Es,{variant:"default"}),x&&e.jsx(Jn,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],open:l,onOpenChange:o,dataSource:u||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function io({activeView:t,onViewChange:n}){const a=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Info"})]})})}const co=[{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 uo(){var u,d;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((d=(u=t.config)==null?void 0:u.rowLimit)==null?void 0:d.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:co.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function mo({isOpen:t,onClose:n}){const a=ht(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:u}=s.useCustomVisual(r),d=A.useMemo(()=>!r||r.trim()===""?null:u("Chart Settings"),[u,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:d&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(d,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function ho(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...l,user:a,tokenContext:n},u=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!u||!u.success)throw new Error((u==null?void 0:u.error)||"Failed to send feedback");return u},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function xo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function po({open:t,onOpenChange:n,feedbackData:a}){var x,b,f,N,T,I;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:u,isSuccess:d,data:m,reset:h}=ho(),p=()=>{const C={...a,userMessage:r.trim()||void 0};i(C)},g=()=>{l(""),c(!1),h(),n(!1)},j={category:a.category,error:{message:(x=a.systemState)==null?void 0:x.errorMessage,sql:(b=a.systemState)==null?void 0:b.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(T=a.systemState)==null?void 0:T.dataSource,filters:(I=a.systemState)==null?void 0:I.dashboardFilters,metadata:a.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:d?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:d?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:C=>l(C.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:u})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(j,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:u,children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:u,className:"min-w-[100px]",children:u?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),d&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ma,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Wt=(t=>(t.QUERY_GENERATION="query-generation",t))(Wt||{});function fo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u,activeCard:d,columns:m,columnsLoading:h,columnsError:p}){var G;const g=s.useEditorStore(Q=>Q.card),j=s.useDashboardStore(Q=>Q.filterValues),x=(j==null?void 0:j.length)||0,{updateCardConfig:b,setCard:f,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:I}=s.useDashboardActions(),[C,S]=A.useState(null),y=s.useEditorStore(Q=>Q.showAIDialog),[E,v]=A.useState(!1),[O,k]=A.useState(!1),[F,w]=A.useState(null),{isConsoleMode:D}=s.useDashboardPreferences(),M=s.useEditorStore(Q=>{var P;return((P=Q.card.customCardPreferences)==null?void 0:P.url)&&Q.card.type==="custom"}),{data:R,errorMessage:L,isLoading:B,isFetching:z,errorSql:$,pagination:_}=s.useDashboardCardQuery(d),Z=(Q,P)=>{const U={...d,paginationConfig:{page:Q+1,pageSize:P}};f(U),N(U)};function se(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(j||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const W=Q=>{if(!g.config)return;if(!Q.length){b(g.id,{...g.config,sortByColumns:[]});return}const P=g.config,U=Q.map(({id:te,desc:le})=>{var oe,ie;const Y=(oe=P.metricColumns)==null?void 0:oe.find(ue=>ue.label===te),q=(ie=P.groupByColumns)==null?void 0:ie.find(ue=>ue.label===te),ae=Y||q;return ae?{id:s.getFieldId("sortBy",ae),name:ae.name,dataType:ae.dataType,label:ae.label,qualifiedEntityName:ae.qualifiedEntityName,entityId:ae.entityId,entityName:ae.entityName,entityType:ae.entityType,role:"sortby",direction:le?"desc":"asc"}:null}).filter(te=>te!==null);b(g.id,{...P,sortByColumns:U})},J=A.useMemo(()=>{var Q,P;return(P=(Q=g.config)==null?void 0:Q.sortByColumns)==null?void 0:P.map(U=>({id:U.label,desc:U.direction==="desc"}))},[(G=g.config)==null?void 0:G.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(oo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u}),a&&se(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&y&&e.jsx(Mt,{variant:"outline"}),e.jsx(io,{activeView:t,onViewChange:n}),i&&e.jsx(lo,{dashboardFilterCount:x,cardFilterCount:u,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(uo,{})}),y&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Lt,{})})]}),!E&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Rt,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:(R==null?void 0:R.records)||[],paginationMetadata:_,onPaginationChange:Z,isLoading:B||z,onSortChange:W,sortState:J})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[D&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:Q=>{const P=s.sanitizeCardId(Q);if(!P){S("Card ID cannot be empty");return}const U=I(g.id,P);if(U.success){T(P);const te={...g,id:P};f(te),N(te),S(null),s.ue.success("Card ID updated successfully")}else S(U.error||"Failed to update Card ID"),s.ue.error(U.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),C&&e.jsx("p",{className:"text-xs text-destructive",children:C})]}),L||$?e.jsx(St,{error:L,errorSql:$,onSendFeedback:()=>{const Q=xo(Wt.QUERY_GENERATION,{cardConfig:g.config,dataSource:d.dataSource,dashboardFilters:j,errorMessage:L,errorSql:$,generatedSql:R==null?void 0:R.sql});w(Q),k(!0)}}):e.jsxs(e.Fragment,{children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(wt,{sql:R==null?void 0:R.sql,error:L,errorSql:$})]})]})})]}),e.jsx(mo,{isOpen:E,onClose:()=>v(!1)}),F&&e.jsx(po,{open:O,onOpenChange:k,feedbackData:F})]})]})}function go({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Os,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const jo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function bo(){var se,W;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(J=>J.showAIDialog),d=s.useDashboardStore(J=>J.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(J=>J.card.type);A.useEffect(()=>jo(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},b=J=>{m(J)},f=s.useEditorStore(J=>J.frame),N=s.useEditorStore(J=>J.card);s.useEditorStore(J=>J.activeTabCardId),s.useEditorStore(J=>J.actions.getAvailableFields);const{addCard:T,removeCard:I,updateCard:C,setActiveCard:S,updateFilters:y}=s.useEditorActions(),{columns:E=[],isLoading:v,error:O}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),F=N,{getFieldsForContainer:w,setFieldsForContainer:D}=Rs(F),{activeField:M,handleDragStart:R,handleDragEnd:L}=ro({activeCardId:f.activeCardId,sourceFields:E,getFieldsForContainer:w,setFieldsForContainer:D}),B=(J,G)=>{G&&y(J,G)},z=J=>{var G;C(J,{config:{...(G=f.cards.find(Q=>Q.id===J))==null?void 0:G.config,filters:void 0}})},$=E,_=J=>{if(!J)return 0;let G=J.conditions.length;return J.groups.forEach(Q=>{G+=_(Q)}),G},Z=_(((se=F==null?void 0:F.config)==null?void 0:se.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:R,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Nl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!u&&e.jsx(_l,{selectedChart:h,onChartChange:b,groupByFields:w("groupBy"),pivotByFields:w("pivotBy"),metricsFields:w("metrics"),sortByFields:w("sortBy")}),e.jsx(fo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:p,onClear:g,onAdvancedToggle:j,onFiltersClick:x,filterCount:Z,activeCard:F,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:E,columnsLoading:v,columnsError:O,getFieldsForContainer:w,cards:f.cards,activeCardId:f.activeCardId,addCard:T,setActiveCard:S})]}),!c&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),F&&e.jsx(no,{cardId:F.id,filters:((W=F.config)==null?void 0:W.filters)||null,onFiltersChange:B,onClearFilters:z,availableFields:$,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(go,{activeField:M||null})})]})}function yo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:u,setOnClose:d}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:p,handleDragCancel:g,sensors:j}=Gn();A.useEffect(()=>{n&&u(n),a&&d(a)},[n,u,a,d]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,T;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function x(N){N<1?i(!1):l||i(!0)}function b(){return e.jsxs(e.Fragment,{children:[e.jsx(Ct,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(il,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Js,{})})]})]})}function f(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(bo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Js,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:b()})}):f()})}function vo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(yo,{onSave:l,onClose:o})})}function No({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(De,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ua,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function Co(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=As();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(No,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function So({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function wo(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=As(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:u,error:d}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const N=s.getDataType(f.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},p=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,j=m.filter(f=>h(f)==="metrics").length,x=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(N,"dashboard",f)};if(u)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const b=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[p.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),p.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),p.map(f=>{const N=l==null?void 0:l.some(T=>{var I;return T.title===f.name||((I=T.column)==null?void 0:I.includes(f.name))});return e.jsx("div",{onClick:()=>x(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(So,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Do(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(wo,{}):e.jsx(Ct,{type:"filter",ColumnsComponent:()=>e.jsx(Co,{})})})]})}function ko(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function To(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(ko,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Do,{})})]})}function Eo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Io({showControls:t=!1,showFooter:n=!0,...a}){if(typeof window>"u")return null;const{preferences:r}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(Eo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Fn,{}),e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(vo,{}),e.jsx(To,{})]})]})]})})]})})}exports.DashboardPlus=Io;exports.ResourceManagementPanel=vt;exports.ScheduleDashboard=it;exports.SelectComponent=Be;exports.ShareDialog=ls;exports.cleanCard=ot;exports.getDashbaordStateWithoutData=ss;