react-semaphor 0.0.548 → 0.0.550

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,14 +1,14 @@
1
- "use strict";var nt=t=>{throw TypeError(t)};var hs=(t,a,n)=>a.has(t)||nt("Cannot "+n);var re=(t,a,n)=>(hs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?nt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(hs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(hs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-DIFWt1VS.js"),M=require("react");require("react-dom");function Mn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Mn(M);var be,Ne,de,fe,ge,Ye,Ns,Nt,Ln=(Nt=class extends s.Subscribable{constructor(a,n){super();Oe(this,ge);Oe(this,be);Oe(this,Ne);Oe(this,de);Oe(this,fe);Be(this,be,a),this.setOptions(n),this.bindMethods(),Fe(this,ge,Ye).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,be).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,be).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this,a)}getCurrentResult(){return re(this,Ne)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this)}mutate(a,n){var r;return Be(this,fe,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,be).getMutationCache().build(re(this,be),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},be=new WeakMap,Ne=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakSet,Ye=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Ne,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Ns=function(a){s.notifyManager.batch(()=>{var n,r,o,l,c,i,d,u;if(re(this,fe)&&this.hasListeners()){const m=re(this,Ne).variables,h=re(this,Ne).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,fe)).onSuccess)==null||r.call(n,a.data,m,h),(l=(o=re(this,fe)).onSettled)==null||l.call(o,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,fe)).onError)==null||i.call(c,a.error,m,h),(u=(d=re(this,fe)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(re(this,Ne))})})},Nt);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Ln(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:l,mutateAsync:o.mutate}}/**
1
+ "use strict";var at=t=>{throw TypeError(t)};var xs=(t,a,n)=>a.has(t)||at("Cannot "+n);var re=(t,a,n)=>(xs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?at("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Fe=(t,a,n,r)=>(xs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Be=(t,a,n)=>(xs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-DIFWt1VS.js"),A=require("react");require("react-dom");function Ln(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Ln(A);var Ne,Ce,de,je,ye,Xe,Cs,Ct,Rn=(Ct=class extends s.Subscribable{constructor(a,n){super();Oe(this,ye);Oe(this,Ne);Oe(this,Ce);Oe(this,de);Oe(this,je);Fe(this,Ne,a),this.setOptions(n),this.bindMethods(),Be(this,ye,Xe).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,Ne).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,Ne).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Be(this,ye,Xe).call(this),Be(this,ye,Cs).call(this,a)}getCurrentResult(){return re(this,Ce)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Fe(this,de,void 0),Be(this,ye,Xe).call(this),Be(this,ye,Cs).call(this)}mutate(a,n){var r;return Fe(this,je,n),(r=re(this,de))==null||r.removeObserver(this),Fe(this,de,re(this,Ne).getMutationCache().build(re(this,Ne),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},Ne=new WeakMap,Ce=new WeakMap,de=new WeakMap,je=new WeakMap,ye=new WeakSet,Xe=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Fe(this,Ce,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Cs=function(a){s.notifyManager.batch(()=>{var n,r,o,l,c,i,d,u;if(re(this,je)&&this.hasListeners()){const m=re(this,Ce).variables,h=re(this,Ce).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,je)).onSuccess)==null||r.call(n,a.data,m,h),(l=(o=re(this,je)).onSettled)==null||l.call(o,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,je)).onError)==null||i.call(c,a.error,m,h),(u=(d=re(this,je)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(re(this,Ce))})})},Ct);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Rn(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:l,mutateAsync:o.mutate}}/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const Rn=s.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
6
+ */const On=s.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
7
7
  * @license lucide-react v0.453.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const On=s.createLucideIcon("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
11
+ */const Fn=s.createLucideIcon("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
12
12
  * @license lucide-react v0.453.0 - ISC
13
13
  *
14
14
  * This source code is licensed under the ISC license.
@@ -18,17 +18,17 @@
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Fn=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"}]]);/**
21
+ */const zn=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"}]]);/**
22
22
  * @license lucide-react v0.453.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */const zn=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"}]]);/**
26
+ */const Pn=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"}]]);/**
27
27
  * @license lucide-react v0.453.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Pn=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"}]]);/**
31
+ */const Vn=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"}]]);/**
32
32
  * @license lucide-react v0.453.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
@@ -38,22 +38,22 @@
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const Vn=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
41
+ */const Un=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
42
42
  * @license lucide-react v0.453.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Un=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"}]]);/**
46
+ */const $n=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"}]]);/**
47
47
  * @license lucide-react v0.453.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const $n=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"}]]);/**
51
+ */const qn=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"}]]);/**
52
52
  * @license lucide-react v0.453.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const qn=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"}]]);/**
56
+ */const Yn=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"}]]);/**
57
57
  * @license lucide-react v0.453.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
@@ -63,7 +63,7 @@
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const Ct=s.createLucideIcon("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
66
+ */const St=s.createLucideIcon("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
67
67
  * @license lucide-react v0.453.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
@@ -73,52 +73,52 @@
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const Kn=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"}]]);/**
76
+ */const Qn=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"}]]);/**
77
77
  * @license lucide-react v0.453.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const at=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"}]]);/**
81
+ */const rt=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"}]]);/**
82
82
  * @license lucide-react v0.453.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
85
85
  * See the LICENSE file in the root directory of this source tree.
86
- */const St=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"}]]);/**
86
+ */const wt=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"}]]);/**
87
87
  * @license lucide-react v0.453.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const wt=s.createLucideIcon("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/**
91
+ */const Dt=s.createLucideIcon("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/**
92
92
  * @license lucide-react v0.453.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const rs=s.createLucideIcon("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
96
+ */const os=s.createLucideIcon("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
97
97
  * @license lucide-react v0.453.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const Ts=s.createLucideIcon("ChartColumnStacked",[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/**
101
+ */const Is=s.createLucideIcon("ChartColumnStacked",[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/**
102
102
  * @license lucide-react v0.453.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const os=s.createLucideIcon("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/**
106
+ */const is=s.createLucideIcon("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/**
107
107
  * @license lucide-react v0.453.0 - ISC
108
108
  *
109
109
  * This source code is licensed under the ISC license.
110
110
  * See the LICENSE file in the root directory of this source tree.
111
- */const Qn=s.createLucideIcon("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/**
111
+ */const Kn=s.createLucideIcon("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/**
112
112
  * @license lucide-react v0.453.0 - ISC
113
113
  *
114
114
  * This source code is licensed under the ISC license.
115
115
  * See the LICENSE file in the root directory of this source tree.
116
- */const Is=s.createLucideIcon("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/**
116
+ */const Ms=s.createLucideIcon("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/**
117
117
  * @license lucide-react v0.453.0 - ISC
118
118
  *
119
119
  * This source code is licensed under the ISC license.
120
120
  * See the LICENSE file in the root directory of this source tree.
121
- */const is=s.createLucideIcon("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/**
121
+ */const ls=s.createLucideIcon("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/**
122
122
  * @license lucide-react v0.453.0 - ISC
123
123
  *
124
124
  * This source code is licensed under the ISC license.
@@ -138,7 +138,7 @@
138
138
  *
139
139
  * This source code is licensed under the ISC license.
140
140
  * See the LICENSE file in the root directory of this source tree.
141
- */const rt=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
141
+ */const ot=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
142
142
  * @license lucide-react v0.453.0 - ISC
143
143
  *
144
144
  * This source code is licensed under the ISC license.
@@ -148,207 +148,207 @@
148
148
  *
149
149
  * This source code is licensed under the ISC license.
150
150
  * See the LICENSE file in the root directory of this source tree.
151
- */const Yn=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"}]]);/**
151
+ */const Xn=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"}]]);/**
152
152
  * @license lucide-react v0.453.0 - ISC
153
153
  *
154
154
  * This source code is licensed under the ISC license.
155
155
  * See the LICENSE file in the root directory of this source tree.
156
- */const Xn=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"}]]);/**
156
+ */const Zn=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"}]]);/**
157
157
  * @license lucide-react v0.453.0 - ISC
158
158
  *
159
159
  * This source code is licensed under the ISC license.
160
160
  * See the LICENSE file in the root directory of this source tree.
161
- */const Zn=s.createLucideIcon("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
161
+ */const ea=s.createLucideIcon("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
162
162
  * @license lucide-react v0.453.0 - ISC
163
163
  *
164
164
  * This source code is licensed under the ISC license.
165
165
  * See the LICENSE file in the root directory of this source tree.
166
- */const Ms=s.createLucideIcon("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
166
+ */const Ls=s.createLucideIcon("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
167
167
  * @license lucide-react v0.453.0 - ISC
168
168
  *
169
169
  * This source code is licensed under the ISC license.
170
170
  * See the LICENSE file in the root directory of this source tree.
171
- */const Dt=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"}]]);/**
171
+ */const Et=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"}]]);/**
172
172
  * @license lucide-react v0.453.0 - ISC
173
173
  *
174
174
  * This source code is licensed under the ISC license.
175
175
  * See the LICENSE file in the root directory of this source tree.
176
- */const ea=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"}]]);/**
176
+ */const sa=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"}]]);/**
177
177
  * @license lucide-react v0.453.0 - ISC
178
178
  *
179
179
  * This source code is licensed under the ISC license.
180
180
  * See the LICENSE file in the root directory of this source tree.
181
- */const sa=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"}]]);/**
181
+ */const ta=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"}]]);/**
182
182
  * @license lucide-react v0.453.0 - ISC
183
183
  *
184
184
  * This source code is licensed under the ISC license.
185
185
  * See the LICENSE file in the root directory of this source tree.
186
- */const ta=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"}]]);/**
186
+ */const na=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"}]]);/**
187
187
  * @license lucide-react v0.453.0 - ISC
188
188
  *
189
189
  * This source code is licensed under the ISC license.
190
190
  * See the LICENSE file in the root directory of this source tree.
191
- */const na=s.createLucideIcon("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
191
+ */const aa=s.createLucideIcon("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
192
192
  * @license lucide-react v0.453.0 - ISC
193
193
  *
194
194
  * This source code is licensed under the ISC license.
195
195
  * See the LICENSE file in the root directory of this source tree.
196
- */const aa=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"}]]);/**
196
+ */const ra=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"}]]);/**
197
197
  * @license lucide-react v0.453.0 - ISC
198
198
  *
199
199
  * This source code is licensed under the ISC license.
200
200
  * See the LICENSE file in the root directory of this source tree.
201
- */const ra=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
201
+ */const oa=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
202
202
  * @license lucide-react v0.453.0 - ISC
203
203
  *
204
204
  * This source code is licensed under the ISC license.
205
205
  * See the LICENSE file in the root directory of this source tree.
206
- */const oa=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"}]]);/**
206
+ */const ia=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"}]]);/**
207
207
  * @license lucide-react v0.453.0 - ISC
208
208
  *
209
209
  * This source code is licensed under the ISC license.
210
210
  * See the LICENSE file in the root directory of this source tree.
211
- */const ia=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"}]]);/**
211
+ */const la=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"}]]);/**
212
212
  * @license lucide-react v0.453.0 - ISC
213
213
  *
214
214
  * This source code is licensed under the ISC license.
215
215
  * See the LICENSE file in the root directory of this source tree.
216
- */const la=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"}]]);/**
216
+ */const ca=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"}]]);/**
217
217
  * @license lucide-react v0.453.0 - ISC
218
218
  *
219
219
  * This source code is licensed under the ISC license.
220
220
  * See the LICENSE file in the root directory of this source tree.
221
- */const Ue=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"}]]);/**
221
+ */const $e=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"}]]);/**
222
222
  * @license lucide-react v0.453.0 - ISC
223
223
  *
224
224
  * This source code is licensed under the ISC license.
225
225
  * See the LICENSE file in the root directory of this source tree.
226
- */const ca=s.createLucideIcon("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
226
+ */const da=s.createLucideIcon("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
227
227
  * @license lucide-react v0.453.0 - ISC
228
228
  *
229
229
  * This source code is licensed under the ISC license.
230
230
  * See the LICENSE file in the root directory of this source tree.
231
- */const da=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"}]]);/**
231
+ */const ua=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"}]]);/**
232
232
  * @license lucide-react v0.453.0 - ISC
233
233
  *
234
234
  * This source code is licensed under the ISC license.
235
235
  * See the LICENSE file in the root directory of this source tree.
236
- */const ua=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"}]]);/**
236
+ */const ma=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"}]]);/**
237
237
  * @license lucide-react v0.453.0 - ISC
238
238
  *
239
239
  * This source code is licensed under the ISC license.
240
240
  * See the LICENSE file in the root directory of this source tree.
241
- */const ma=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"}]]);/**
241
+ */const ha=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"}]]);/**
242
242
  * @license lucide-react v0.453.0 - ISC
243
243
  *
244
244
  * This source code is licensed under the ISC license.
245
245
  * See the LICENSE file in the root directory of this source tree.
246
- */const ha=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"}]]);/**
246
+ */const xa=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"}]]);/**
247
247
  * @license lucide-react v0.453.0 - ISC
248
248
  *
249
249
  * This source code is licensed under the ISC license.
250
250
  * See the LICENSE file in the root directory of this source tree.
251
- */const Et=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"}]]);/**
251
+ */const Tt=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"}]]);/**
252
252
  * @license lucide-react v0.453.0 - ISC
253
253
  *
254
254
  * This source code is licensed under the ISC license.
255
255
  * See the LICENSE file in the root directory of this source tree.
256
- */const xa=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"}]]);/**
256
+ */const pa=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"}]]);/**
257
257
  * @license lucide-react v0.453.0 - ISC
258
258
  *
259
259
  * This source code is licensed under the ISC license.
260
260
  * See the LICENSE file in the root directory of this source tree.
261
- */const pa=s.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
261
+ */const fa=s.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
262
262
  * @license lucide-react v0.453.0 - ISC
263
263
  *
264
264
  * This source code is licensed under the ISC license.
265
265
  * See the LICENSE file in the root directory of this source tree.
266
- */const ot=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"}]]);/**
266
+ */const it=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"}]]);/**
267
267
  * @license lucide-react v0.453.0 - ISC
268
268
  *
269
269
  * This source code is licensed under the ISC license.
270
270
  * See the LICENSE file in the root directory of this source tree.
271
- */const Ls=s.createLucideIcon("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/**
271
+ */const Rs=s.createLucideIcon("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/**
272
272
  * @license lucide-react v0.453.0 - ISC
273
273
  *
274
274
  * This source code is licensed under the ISC license.
275
275
  * See the LICENSE file in the root directory of this source tree.
276
- */const fa=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"}]]);/**
276
+ */const ga=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"}]]);/**
277
277
  * @license lucide-react v0.453.0 - ISC
278
278
  *
279
279
  * This source code is licensed under the ISC license.
280
280
  * See the LICENSE file in the root directory of this source tree.
281
- */const ga=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
281
+ */const ja=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
282
282
  * @license lucide-react v0.453.0 - ISC
283
283
  *
284
284
  * This source code is licensed under the ISC license.
285
285
  * See the LICENSE file in the root directory of this source tree.
286
- */const it=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"}]]);/**
286
+ */const lt=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"}]]);/**
287
287
  * @license lucide-react v0.453.0 - ISC
288
288
  *
289
289
  * This source code is licensed under the ISC license.
290
290
  * See the LICENSE file in the root directory of this source tree.
291
- */const lt=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"}]]);/**
291
+ */const ct=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"}]]);/**
292
292
  * @license lucide-react v0.453.0 - ISC
293
293
  *
294
294
  * This source code is licensed under the ISC license.
295
295
  * See the LICENSE file in the root directory of this source tree.
296
- */const ja=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"}]]);/**
296
+ */const ya=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"}]]);/**
297
297
  * @license lucide-react v0.453.0 - ISC
298
298
  *
299
299
  * This source code is licensed under the ISC license.
300
300
  * See the LICENSE file in the root directory of this source tree.
301
- */const ya=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"}]]);/**
301
+ */const va=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"}]]);/**
302
302
  * @license lucide-react v0.453.0 - ISC
303
303
  *
304
304
  * This source code is licensed under the ISC license.
305
305
  * See the LICENSE file in the root directory of this source tree.
306
- */const va=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"}]]);/**
306
+ */const ba=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"}]]);/**
307
307
  * @license lucide-react v0.453.0 - ISC
308
308
  *
309
309
  * This source code is licensed under the ISC license.
310
310
  * See the LICENSE file in the root directory of this source tree.
311
- */const Rs=s.createLucideIcon("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/**
311
+ */const Os=s.createLucideIcon("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/**
312
312
  * @license lucide-react v0.453.0 - ISC
313
313
  *
314
314
  * This source code is licensed under the ISC license.
315
315
  * See the LICENSE file in the root directory of this source tree.
316
- */const Tt=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"}]]);/**
316
+ */const It=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"}]]);/**
317
317
  * @license lucide-react v0.453.0 - ISC
318
318
  *
319
319
  * This source code is licensed under the ISC license.
320
320
  * See the LICENSE file in the root directory of this source tree.
321
- */const ba=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"}]]);/**
321
+ */const Na=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"}]]);/**
322
322
  * @license lucide-react v0.453.0 - ISC
323
323
  *
324
324
  * This source code is licensed under the ISC license.
325
325
  * See the LICENSE file in the root directory of this source tree.
326
- */const It=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"}]]);/**
326
+ */const Mt=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"}]]);/**
327
327
  * @license lucide-react v0.453.0 - ISC
328
328
  *
329
329
  * This source code is licensed under the ISC license.
330
330
  * See the LICENSE file in the root directory of this source tree.
331
- */const Na=s.createLucideIcon("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
331
+ */const Ca=s.createLucideIcon("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
332
332
  * @license lucide-react v0.453.0 - ISC
333
333
  *
334
334
  * This source code is licensed under the ISC license.
335
335
  * See the LICENSE file in the root directory of this source tree.
336
- */const $e=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"}]]);/**
336
+ */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"}]]);/**
337
337
  * @license lucide-react v0.453.0 - ISC
338
338
  *
339
339
  * This source code is licensed under the ISC license.
340
340
  * See the LICENSE file in the root directory of this source tree.
341
- */const qe=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"}]]);/**
341
+ */const Ye=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"}]]);/**
342
342
  * @license lucide-react v0.453.0 - ISC
343
343
  *
344
344
  * This source code is licensed under the ISC license.
345
345
  * See the LICENSE file in the root directory of this source tree.
346
- */const Ca=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"}]]);/**
346
+ */const Sa=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"}]]);/**
347
347
  * @license lucide-react v0.453.0 - ISC
348
348
  *
349
349
  * This source code is licensed under the ISC license.
350
350
  * See the LICENSE file in the root directory of this source tree.
351
- */const Sa=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"}]]);/**
351
+ */const wa=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"}]]);/**
352
352
  * @license lucide-react v0.453.0 - ISC
353
353
  *
354
354
  * This source code is licensed under the ISC license.
@@ -358,7 +358,7 @@
358
358
  *
359
359
  * This source code is licensed under the ISC license.
360
360
  * See the LICENSE file in the root directory of this source tree.
361
- */const wa=s.createLucideIcon("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
361
+ */const Da=s.createLucideIcon("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
362
362
  * @license lucide-react v0.453.0 - ISC
363
363
  *
364
364
  * This source code is licensed under the ISC license.
@@ -368,27 +368,27 @@
368
368
  *
369
369
  * This source code is licensed under the ISC license.
370
370
  * See the LICENSE file in the root directory of this source tree.
371
- */const ls=s.createLucideIcon("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/**
371
+ */const cs=s.createLucideIcon("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/**
372
372
  * @license lucide-react v0.453.0 - ISC
373
373
  *
374
374
  * This source code is licensed under the ISC license.
375
375
  * See the LICENSE file in the root directory of this source tree.
376
- */const Mt=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"}]]);/**
376
+ */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"}]]);/**
377
377
  * @license lucide-react v0.453.0 - ISC
378
378
  *
379
379
  * This source code is licensed under the ISC license.
380
380
  * See the LICENSE file in the root directory of this source tree.
381
- */const Da=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
381
+ */const Ea=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
382
382
  * @license lucide-react v0.453.0 - ISC
383
383
  *
384
384
  * This source code is licensed under the ISC license.
385
385
  * See the LICENSE file in the root directory of this source tree.
386
- */const Ze=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"}]]);/**
386
+ */const es=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"}]]);/**
387
387
  * @license lucide-react v0.453.0 - ISC
388
388
  *
389
389
  * This source code is licensed under the ISC license.
390
390
  * See the LICENSE file in the root directory of this source tree.
391
- */const Os=s.createLucideIcon("Tornado",[["path",{d:"M21 4H3",key:"1hwok0"}],["path",{d:"M18 8H6",key:"41n648"}],["path",{d:"M19 12H9",key:"1g4lpz"}],["path",{d:"M16 16h-6",key:"1j5d54"}],["path",{d:"M11 20H9",key:"39obr8"}]]);/**
391
+ */const Fs=s.createLucideIcon("Tornado",[["path",{d:"M21 4H3",key:"1hwok0"}],["path",{d:"M18 8H6",key:"41n648"}],["path",{d:"M19 12H9",key:"1g4lpz"}],["path",{d:"M16 16h-6",key:"1j5d54"}],["path",{d:"M11 20H9",key:"39obr8"}]]);/**
392
392
  * @license lucide-react v0.453.0 - ISC
393
393
  *
394
394
  * This source code is licensed under the ISC license.
@@ -398,12 +398,12 @@
398
398
  *
399
399
  * This source code is licensed under the ISC license.
400
400
  * See the LICENSE file in the root directory of this source tree.
401
- */const Se=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"}]]);/**
401
+ */const we=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"}]]);/**
402
402
  * @license lucide-react v0.453.0 - ISC
403
403
  *
404
404
  * This source code is licensed under the ISC license.
405
405
  * See the LICENSE file in the root directory of this source tree.
406
- */const je=s.createLucideIcon("Users",[["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"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Lt(c))}})}})}}function Lt(t){return{...t,customCfg:Ea(t.customCfg),data:[]}}function Ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ta(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Cs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ia(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:p}=s.useSemaphorContext();async function g(){d(!0);const x=Bs(h),v=await Ta(t,x,f,p==null?void 0:p.accessToken);v&&(l([...o||[],v]),c(v.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,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=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&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:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ma(){const[t,a]=M.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ia(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(p=>p.id!==m);o(f||[]),l("original")}}async function u(m){const h=n==null?void 0:n.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});o(h||[]);const f={...m,isDefault:!m.isDefault};await Cs(f,c==null?void 0:c.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==m.id){const g={...p,isDefault:!1};await Cs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(oa,{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"}),n==null?void 0:n.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(),u(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(),d(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 Rt(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ot(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const m=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=m;const f=`${o}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function La({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ot()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ct=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Ra(),[i,d]=M.useState(""),[u,m]=M.useState(ct[0].value),[h,f]=M.useState("06:00"),[p,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{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-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:x=>{g(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ct,value:u,onValueChange:x=>m(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:h,onChange:x=>f(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:u,time:h,subject:p}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(dt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(dt,{tooltip:`${x.endUserEmail}`,children:e.jsx(pa,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const dt=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Ra(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,l]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:u},{data:f,isLoading:p,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...D}=Rt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:p,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function cs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function Ft(){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,a)=>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"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Oa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Fa=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Va=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ua=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Oa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Ka(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Fa((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Qa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>za((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Pa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>_a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Ya(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Va((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function Xa(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ua((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function Za(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>$a((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function er(t,a){return Za(ee.VISUAL,t,a)}function zt(){const[t,a]=M.useState(new Map),n=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=M.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Pt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Ka(t),c=Qa(t,a),i=Wa(t),d=Ja(),u=Ya(),m={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[m[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function sr(t,a){return Pt(ee.DASHBOARD,t,a)}function tr(t,a){return Pt(ee.VISUAL,t,a)}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ar({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var E;const{selectVisual:f}=s.useManagementActions(),p=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&p,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),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:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(ya,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{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 _t({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function es({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?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":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Vt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){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(l=>n(l.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:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function Ut({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 $t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.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(je,{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:l(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:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.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 n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function or(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ir({user:t}){return Gt(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 lr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=rr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(es,{currentRole:u,onRoleChange:h=>{l(t.id,a.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:xe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){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"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?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 ur({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=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((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.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 (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.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:u.map((f,p)=>{const g=xe(f.role,n(""));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:g})]},p)})})]}),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((f,p)=>{const g=xe(f.role,n(""));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:g})]},p)})})]}),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((f,p)=>{const g=xe(f.role,n(""));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:g})]},p)})})]}),!i.length&&!d.length&&!u.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((d,u)=>{var p,g;const m=((p=a.find(x=>x.id===d.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",f=xe(d.role,n(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:f})]},u)}),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((d,u)=>{const m=xe(d.role,n(""));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})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=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:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,p;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((p=a.find(g=>g.id===i.tenantUserId))==null?void 0:p.type)||"",h=xe(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.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,d)=>{const u=xe(i.role,n(""));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:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mr({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?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(ir,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(es,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(lr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>p(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(dr,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const S=m.some(D=>D.id===E),N=h.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,R=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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(ur,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===C.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(mr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?or(E,t,l):void 0,N=R.includes(E.id),D=!!S,w=D&&!N,L=m.some(A=>A.id===E.id),k=m.find(A=>A.id===E.id),O=r(E.type);return e.jsx(hr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:L,selectedUser:k,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.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 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(Se,{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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.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 De=()=>[{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 xr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=De().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:m,f=a.role!=="NONE"&&!l&&(!o||o.newRole===m),p=o!==null&&o.newRole!==m,g=l,x=m==="NONE"||!m,v=b=>{switch(b){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(Ca,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!g&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||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(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||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:u.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Qt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,p=(x,v)=>{l(x,v)},g=()=>{c()};return e.jsx(xr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const pr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=fr(c),m=Xa(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function gr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var W,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:D}=we({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),k=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=f.some(Z=>Z.id===$),U=p.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const P=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(_t,{value:u,onChange:m}),e.jsx(Vt,{selectedUsers:f,selectedUserObjects:k,onRemove:O,onRoleChange:A,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx($t,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:De}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Qt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function ut({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:k,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=m.some(K=>K.id===G),te=h.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},T=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},P=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return p==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:p==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=D.filter(G=>m.some(Z=>Z.id===G.id)),q=L||O,U=k||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{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(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(at,{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(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{value:i,onChange:u}),e.jsx(Vt,{selectedUsers:m,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:h,allUsers:D,onRemove:F}),e.jsx($t,{usersToUpdate:f,allUsers:D,onRemove:z,getRoleOptions:De}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:D,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Qt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Y,allUsersToUpdate:p==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||p==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||p==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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(at,{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"})]})})]})]})}const Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),m=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function mt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const p=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,k,O,A;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!p||i==="specific_tenant_users"&&!p?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},D=()=>{var L,k,O,A;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const F={...T,updateAccess:!0};l(F)}}}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}},w=()=>{var L,k,O,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function jr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:p,isCurrentStateValid:g}=Wt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const E=d.length+u.length+m.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const E=f();E&&p(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&p(E)&&o(E)}else{const E=i.role;if(h===E){const N=f();if(N&&p(N)){const D={...N,removeAccess:!0};o(D)}}else{const N=f();if(N&&p(N)){const D={...N,updateAccess:!0};o(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,D,w,L;const{currentUser:d}=cs(),[u,m]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=M.useCallback(()=>{p.resetShareState(),l()},[p,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,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(qe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"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."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:k=>{const O=k;p.setSelectedTab(O),p.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(gr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,isRemoving:r})})}),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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})})]}):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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(mt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(mt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(jr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Yt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m,tenantId:h}=t;if(u&&u.length>0){const f=Ce(n,r,u.map(p=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(m&&m.length>0&&m.forEach(f=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:h,role:f.newRole}]);o(p,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Xt(t,a,n,r){var u,m,h,f,p,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Ce(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(j){const b=Ce(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(j){const b=Ce(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(p=i==null?void 0:i.shares)==null?void 0:p.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function yr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Fs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(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 d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Nr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function ht(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Cr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function Sr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Fs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:M.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=br(m),t(p));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Nr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function zs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=er((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a);return Cr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=M.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(h,C,"end"),c(!0),d(C.id),m(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:p,handleAddLibraryVisual:g,getUpdatedFrame:Sr().getUpdatedFrame,refetch:f.refetch}}function wr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[f,p]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=zs(),{resources:S,isLoading:N,isError:D,createResource:w,updateResource:L,deleteResource:k,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=tr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Y}=vr((m==null?void 0:m.id)||null,A,T);cs();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),p(!0)},U=()=>{g&&k(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=zt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{E(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{h(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ft,{}):D?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:n?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:o,onChange:B=>l(B.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:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),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:B=>a(B.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:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(ar,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:B=>{!B&&y||(p(B),B||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 "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var E;const{selectDashboard:f}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),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:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{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:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{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 Dr({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 Er(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[l,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,f]=M.useState(null),[p,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:D,updateResource:w,deleteResource:L,duplicateResource:k,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:F,removeResourceShares:z}=sr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=yr((h==null?void 0:h.id)||null,F,z),{currentUser:Y}=cs(),W=E.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&D({title:l,description:i,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),k(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=zt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=E.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{f(K),Y==null||Y.type,m(!0)};return we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ft,{}):N?e.jsx(Dr,{onRetry:()=>window.location.reload()}):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: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:l,onChange:K=>c(K.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:K=>d(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:K=>n(K.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:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ra,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(kr,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:K=>{!K&&A||(g(K),K||v(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:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:c}=cs(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=qt(a,{enabled:t}),h=p=>{},f=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,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":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 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-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Er,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(wr,{})})]})})]})})}function Tr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,m]=M.useState(!1),h=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),x=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:D,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>D||w,[D,w]),k=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,F),C(F.id)},O=()=>{E(!0)};async function A(){if(m(!0),!r||!o)return;const T=Bs(l),F=JSON.stringify(T),z={...o,template:F,filterValues:p};await Cs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),m(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(La,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(Ma,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(It,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:h,onClose:()=>f(!1)})]})]})}function Ir({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ue.useRef(null),[h,f]=ue.useState(!1),[p,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{m.current&&g(m.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,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:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:p},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(Tt,{className:s.cn("size-3.5 opacity-50",o&&"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(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ja,{className:"size-4"});if(t==="Table")return e.jsx(ls,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function p(){return e.jsxs(s.Select,{disabled:u,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",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"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(Tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function g(){return e.jsx(Ir,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?p():g()})})}function Ar({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function p(x,v){var R;const j=s.createSqlGenConfig(x,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;m(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(h(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,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:g()})]})}function Ps({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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(Ue,{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(Ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{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 xs({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Ps,{column:t}),e.jsx("span",{children:t.column_name})]})}function Mr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Lr({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(xs,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(xs,{column:a})}),e.jsx(Mr,{id:a.column_name,type:"column",children:e.jsx(xs,{column:a})})]})}const ps={id:"__placeholder__",role:"groupby",type:"string"},fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"metric",type:"number"},js={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Ee="droppable-group-by",Te="droppable-metrics",Ie="droppable-pivot-by",ss="sortable-group-by",Ss="sortable-metrics",ts="sortable-pivot-by",ws="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Rr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:T}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&T){const z=T.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==ps.id);q.splice($,0,ps),d(q)}else if(T.id===Ee){c(a.length);const $=[...a,ps];d($),u(n),m(r)}}if(Y||W){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==fs.id);q.splice($,0,fs),h(q)}else if(T.id===Ie){c(l.length);const $=[...l,fs];h($),d(a),u(n),m(r)}}if(P||Y){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==gs.id);q.splice($,0,gs),u(q)}else if(T.id===Te){c(n.length);const $=[...n,gs];u($),m(r),d(a),h(l)}}if(S(_)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==js.id);q.splice($,0,js),m(q)}else if(T.id===ws){c(r.length);const $=[...r,js];m($),u(n),d(a),h(l)}}}else d(a),u(n),m(r),h(l)};function E(I){i(I.active.id),c(null),d(a),u(n),m(r),h(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:pe(T),name:T,label:He(T,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),p(z)}function D(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],F=t!==null?t:l.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,F),g(y)}function k(I){var z,_,P,Y,W,V,$,q;const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(T.id===Ee||((z=T.data.current)==null?void 0:z.type)===ss)&&w(U),(Q||G)&&(T.id===Ie||((_=T.data.current)==null?void 0:_.type)===ts)?D(U):(H||Q)&&(T.id===Te||((P=T.data.current)==null?void 0:P.type)===Ss)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===ws||((Y=T.data.current)==null?void 0:Y.type)===ks)&&L(U)}if(T&&((W=T.data.current)==null?void 0:W.type)===ss&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(T&&((V=T.data.current)==null?void 0:V.type)===ts&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),H=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...l],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===Ss&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),i(null),c(null),d(a),u(n),m(r),h(l)}function O(I){const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)===_s&&T){const z=o.findIndex(P=>Ve(P.columnId)===y.id),_=o.findIndex(P=>Ve(P.columnId)===T.id);if(z!==-1&&_!==-1&&z!==_){const P=[...o],[Y]=P.splice(z,1);P.splice(_,0,Y),x(P)}}}function A(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:k,handleDragStart:E,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${_s}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Or({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),m=s.useEditorStore(y=>y.selectedTableName),h=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function D(y){var T;if(l){const F=s.createSqlGenConfig(y,o);C(F);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",E,d||"");_&&(j(_),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(m||N)&&c?(p({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===m||y.datamodelName===N)))!==void 0}function A(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Lr,{onClick:D,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(xa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:m,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:k,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Or,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":k?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),h(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:F,showNone:!0,onChange:$,isError:D,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!T&&(!c||c==="none")&&(!l||l==="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 J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",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]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:W,items:p,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="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:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(fa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const p=f.toString();navigator.clipboard.writeText(p),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!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 ${a}`,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 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&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 nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(la,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{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-[600px]",children:e.jsx(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},xt=M.createContext&&M.createContext(rn),Br=["attr","size","title"];function Fr(t,a){if(t==null)return{};var n=zr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function zr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function ns(){return ns=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ns.apply(this,arguments)}function pt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function as(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?pt(Object(n),!0).forEach(function(r){Pr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pr(t,a,n){return a=_r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function _r(t){var a=Vr(t,"string");return typeof a=="symbol"?a:a+""}function Vr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function on(t){return t&&t.map((a,n)=>M.createElement(a.tag,as({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Ur,ns({attr:as({},t.attr)},a),on(t.child))}function Ur(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=Fr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ns({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:as(as({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&M.createElement("title",null,l),t.children)};return xt!==void 0?M.createElement(xt.Consumer,null,n=>a(n)):a(rn)}function $r(t){return Me({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 ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),f=r.cards.find(x=>x.id===l),p=M.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);M.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let v=h.current[l];if(!v){const j=p();v=c.editor.createModel(j,t),h.current[l]=v}m.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,p]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(x,v){if(m.current=x,!h.current[o.id]){const j=x.getModel(),b=p();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function qr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function l(c){n(c),s.isObjectEmpty(a)||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:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}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:n})}function Hr({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 Vs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Fs(((c=n.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),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=zs();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=zs(),c=s.useSelectedVisual(),i=nr(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Us(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}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 ds(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:p,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),p(void 0),d(""),u(""),m({}),g("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 Qr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.sql}),d=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:L,isError:k,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);h(P)}},[N,h,g]),M.useEffect(()=>{(D||w)&&S(!0),(k||L)&&S(!1),k&&(h([]),g(""))},[D,w,N,g,k,L,S,h,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),E(!1))},[R,I,E,A,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
406
+ */const ve=s.createLucideIcon("Users",[["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"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Rt(c))}})}})}}function Rt(t){return{...t,customCfg:Ta(t.customCfg),data:[]}}function Ta(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ia(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Ss(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ma(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:p}=s.useSemaphorContext();async function g(){d(!0);const x=Bs(h),v=await Ia(t,x,f,p==null?void 0:p.accessToken);v&&(l([...o||[],v]),c(v.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,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=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&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:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function La(){const[t,a]=A.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ma(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(p=>p.id!==m);o(f||[]),l("original")}}async function u(m){const h=n==null?void 0:n.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});o(h||[]);const f={...m,isDefault:!m.isDefault};await Ss(f,c==null?void 0:c.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==m.id){const g={...p,isDefault:!1};await Ss(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(ia,{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"}),n==null?void 0:n.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(),u(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(),d(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 Ot(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ft(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Ot();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const m=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=m;const f=`${o}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function Ra({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ft()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const dt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Oa(),[i,d]=A.useState(""),[u,m]=A.useState(dt[0].value),[h,f]=A.useState("06:00"),[p,g]=A.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{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-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:x=>{g(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:dt,value:u,onValueChange:x=>m(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:h,onChange:x=>f(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:u,time:h,subject:p}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(ut,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(ut,{tooltip:`${x.endUserEmail}`,children:e.jsx(fa,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const ut=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Oa(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[o,l]=A.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:u},{data:f,isLoading:p,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...k}=Ot(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:k};a("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(D,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:p,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function ds(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function zt(){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,a)=>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"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Fa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},za=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Va=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Ua=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Ya(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Fa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Qa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>za((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Ka(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Pa((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Va((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>_a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Xa(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ua((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function Za(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>$a((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function er(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>qa((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function sr(t,a){return er(ee.VISUAL,t,a)}function Pt(){const[t,a]=A.useState(new Map),n=A.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=A.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=A.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Vt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Qa(t),c=Ka(t,a),i=Wa(t),d=Ja(),u=Xa(),m={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[m[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function tr(t,a){return Vt(ee.DASHBOARD,t,a)}function nr(t,a){return Vt(ee.VISUAL,t,a)}function ar(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function rr({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var E;const{selectVisual:f}=s.useManagementActions(),p=s.useIsVisualSelected(t.id),[g,x]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&p,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),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:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(va,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(we,{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 _t({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function ss({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?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":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Ut({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){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(l=>n(l.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:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function $t({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 qt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.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(ve,{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:l(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:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function Yt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=A.useRef(null);return A.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.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 n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function or(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ir(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function lr({user:t}){return Gt(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 cr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=or((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ss,{currentRole:u,onRoleChange:h=>{l(t.id,a.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:pe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function dr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ur({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){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"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?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 mr({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=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((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=pe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.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 (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=pe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.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:u.map((f,p)=>{const g=pe(f.role,n(""));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:g})]},p)})})]}),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((f,p)=>{const g=pe(f.role,n(""));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:g})]},p)})})]}),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((f,p)=>{const g=pe(f.role,n(""));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:g})]},p)})})]}),!i.length&&!d.length&&!u.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((d,u)=>{var p,g;const m=((p=a.find(x=>x.id===d.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",f=pe(d.role,n(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:f})]},u)}),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((d,u)=>{const m=pe(d.role,n(""));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})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=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:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,p;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((p=a.find(g=>g.id===i.tenantUserId))==null?void 0:p.type)||"",h=pe(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.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,d)=>{const u=pe(i.role,n(""));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:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function hr({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function xr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?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(lr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(cr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>p(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(dr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(ur,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const S=m.some(k=>k.id===E),N=h.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,R=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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(mr,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===C.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(hr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?ir(E,t,l):void 0,N=R.includes(E.id),k=!!S,w=k&&!N,L=m.some(M=>M.id===E.id),D=m.find(M=>M.id===E.id),O=r(E.type);return e.jsx(xr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:D,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Qt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.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 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(we,{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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.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 Ee=()=>[{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 pr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Ee().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:m,f=a.role!=="NONE"&&!l&&(!o||o.newRole===m),p=o!==null&&o.newRole!==m,g=l,x=m==="NONE"||!m,v=b=>{switch(b){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(Sa,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!g&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||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(ve,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||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:u.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Kt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,p=(x,v)=>{l(x,v)},g=()=>{c()};return e.jsx(pr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const fr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function gr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>fr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=A.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=gr(c),m=Za(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function jr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var K,_;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:k}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});A.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,G;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(G=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:G[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),D=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,Y;const q=f.some(Z=>Z.id===$),U=p.includes($),G=(Y=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:Y.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):G||j.addSelectedUser({id:$,role:"VIEWER"})},M=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},B=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(_=(K=N==null?void 0:N.shares)==null?void 0:K.orgUsersOnly)==null?void 0:_[0];A.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&j.setOrgWideRole(V.role)},[b,V,j]);const P=k,X=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(we,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(ve,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(_t,{value:u,onChange:m}),e.jsx(Ut,{selectedUsers:f,selectedUserObjects:D,onRemove:O,onRoleChange:M,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx(qt,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:X,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:M,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Kt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:B,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function mt({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=Ya({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=A.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=Y=>{var te,ae,se,oe;E(Y);let Z;if(Y==="specific_tenant_users"?Z="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&j.setCurrentMode("allTenants")),Y==="all_tenant_users"){const H=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];H&&H.role!==void 0&&j.setTenantWideRole(H.role)}else if(Y==="all_tenants"){const H=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];H&&H.role!==void 0&&j.setAllTenantsRole(H.role)}},N=Y=>{j.setSelectedTenant(Y)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:D,isLoadingShares:O,isErrorLoadingShares:M}=De({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=Y=>{var se,oe;const Z=m.some(H=>H.id===Y),te=h.includes(Y),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(H=>H.tenantUserId===Y);Z?j.removeSelectedUser(Y):te?j.removeUserFromRemove(Y):ae||j.addSelectedUser({id:Y,role:"VIEWER"})},y=(Y,Z)=>{j.updateSelectedUserRole(Y,Z)},T=Y=>{j.addUserToRemove(Y),j.removeSelectedUser(Y)},B=Y=>{j.removeUserFromRemove(Y)},z=Y=>{j.removeUserFromUpdate(Y)},V=(Y,Z,te)=>{j.addUserToUpdate({id:Y,currentRole:Z,newRole:te})},P=(Y,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},X=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},_=(()=>{var Y,Z,te,ae;return p==="allTenants"?(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:Z[0]:p==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();A.useEffect(()=>{var Y,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=k.filter(Y=>m.some(Z=>Z.id===Y.id)),q=L||O,U=D||M,G=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Qt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(ve,{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(we,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(rt,{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(we,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),G()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{value:i,onChange:u}),e.jsx(Ut,{selectedUsers:m,selectedUserObjects:$,onRemove:Y=>I(Y),onRoleChange:y,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:h,allUsers:k,onRemove:B}),e.jsx(qt,{usersToUpdate:f,allUsers:k,onRemove:z,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Kt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:X,allUsersToUpdate:p==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||g!==_.role)||p==="allTenants"&&((_==null?void 0:_.role)===void 0||x!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||p==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="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(rt,{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"})]})})]})]})}const Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),m=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function ht({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const p=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,D,O,M;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!p||i==="specific_tenant_users"&&!p?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},k=()=>{var L,D,O,M;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const B={...T,updateAccess:!0};l(B)}}}else if(i==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(x===y)u==null||u();else{const B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}},w=()=>{var L,D,O,M;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ve,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function yr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:p,isCurrentStateValid:g}=Wt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const E=d.length+u.length+m.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const E=f();E&&p(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&p(E)&&o(E)}else{const E=i.role;if(h===E){const N=f();if(N&&p(N)){const k={...N,removeAccess:!0};o(k)}}else{const N=f();if(N&&p(N)){const k={...N,updateAccess:!0};o(k)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,k,w,L;const{currentUser:d}=ds(),[u,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(k=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=A.useCallback(()=>{p.resetShareState(),l()},[p,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,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(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"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."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:D=>{const O=D;p.setSelectedTab(O),p.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(jr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,isRemoving:r})})}),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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),isSharing:n,isUpdating:o,isRemoving:r})})})]}):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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(ht,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(ht,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(yr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Se(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Xt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Se(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m,tenantId:h}=t;if(u&&u.length>0){const f=Se(n,r,u.map(p=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(m&&m.length>0&&m.forEach(f=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:h,role:f.newRole}]);o(p,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Se(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Se(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Zt(t,a,n,r){var u,m,h,f,p,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Se(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(j){const b=Se(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(j){const b=Se(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(p=i==null?void 0:i.shares)==null?void 0:p.orgUsersOnly)==null?void 0:g[0];if(j){const b=Se(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function Nr(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function zs(t){const[a,n]=A.useState(null),[r,o]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){n(null),o(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 d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Cr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function xt(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Sr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function wr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=zs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:A.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=Nr(m),t(p));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Cr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function Ps(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=sr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=A.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await xt((t==null?void 0:t.accessToken)||"",x.id,a);return Sr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await xt((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(h,C,"end"),c(!0),d(C.id),m(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:p,handleAddLibraryVisual:g,getUpdatedFrame:wr().getUpdatedFrame,refetch:f.refetch}}function Dr(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[f,p]=A.useState(!1),[g,x]=A.useState(null),[v,j]=A.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=Ps(),{resources:S,isLoading:N,isError:k,createResource:w,updateResource:L,deleteResource:D,duplicateResource:O,shareResource:M,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:B,isRemovingShares:z,isUpdatingShares:V}=nr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:X}=br((m==null?void 0:m.id)||null,M,T);ds();const K=S.filter(F=>{var J,ie;return((J=F==null?void 0:F.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=F==null?void 0:F.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),_=F=>new Date(F).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=F=>{x(F),p(!0)},U=()=>{g&&D(g.id)},{startUpdating:G,stopUpdating:Q,isUpdating:Y}=Pt(),Z=(F,J)=>{const ie=J.title!==void 0?"title":"description";G(F,ie),L({resourceId:F,data:J},{onSuccess:()=>{Q(F,ie)},onError:()=>{Q(F,ie)}})},te=F=>{j(F),O(F,{onSettled:()=>j(null)})},ae=F=>{R(F)},se=F=>{E(F)},oe=F=>{const J=S.find(ie=>ie.id===F);J&&L({resourceId:F,data:{isPrivate:!J.isPrivate}})},H=F=>{h(F),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(zt,{}):k?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:n?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:o,onChange:F=>l(F.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:F=>i(F.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),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:F=>a(F.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:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ls,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):K.map(F=>e.jsx(rr,{visual:F,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:H,isDeleting:y,isDuplicating:v===F.id,isTitleUpdating:Y(F.id,"title"),isDescriptionUpdating:Y(F.id,"description"),formatDate:_},F.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:B,isRemoving:z,isUpdating:V,onClose:()=>{u(!1),h(null)},onRemoveAccess:X}),e.jsx(s.AlertDialog,{open:f,onOpenChange:F=>{!F&&y||(p(F),F||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 "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:F=>{F.preventDefault(),F.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var E;const{selectDashboard:f}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[g,x]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),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:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(ve,{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:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(we,{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 Er({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 Tr(t){const[a,n]=A.useState(""),[r,o]=A.useState(!1),[l,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,f]=A.useState(null),[p,g]=A.useState(!1),[x,v]=A.useState(null),[j,b]=A.useState(null),C=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:k,updateResource:w,deleteResource:L,duplicateResource:D,isCreating:O,isDeleting:M,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:B,removeResourceShares:z}=tr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:P}=vr((h==null?void 0:h.id)||null,B,z),{currentUser:X}=ds(),K=E.filter(H=>{var F,J;return((F=H==null?void 0:H.title)==null?void 0:F.toLowerCase().includes(a.toLowerCase()))||((J=H==null?void 0:H.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),_=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&k({title:l,description:i,isPrivate:!1})},q=H=>{var F;(F=t.onLoadDashboard)==null||F.call(t,H)},U=H=>{v(H),g(!0)},G=()=>{x&&L(x.id)},Q=H=>{b(H),D(H,{onSettled:()=>b(null)})},{startUpdating:Y,stopUpdating:Z,isUpdating:te}=Pt(),ae=(H,F)=>{const J=F.title!==void 0?"title":"description";Y(H,J),w({resourceId:H,data:F},{onSuccess:()=>{Z(H,J)},onError:()=>{Z(H,J)}})},se=H=>{const F=E.find(J=>J.id===H);F&&w({resourceId:H,data:{isPrivate:!F.isPrivate}})},oe=H=>{f(H),X==null||X.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(zt,{}):N?e.jsx(Er,{onRetry:()=>window.location.reload()}):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: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:l,onChange:H=>c(H.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:H=>d(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:H=>n(H.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:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(oa,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):K.map(H=>e.jsx(kr,{dashboard:H,isDeleting:M,isDuplicating:j===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:H=>{!H&&M||(g(H),H||v(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:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),G()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function en({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:c}=ds(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=Yt(a,{enabled:t}),h=p=>{},f=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,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",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 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-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Tr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Dr,{})})]})})]})})}function Ir(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,m]=A.useState(!1),h=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),x=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:k,endUserId:w}=A.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=A.useMemo(()=>k||w,[k,w]),D=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},B={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,B),C(B.id)},O=()=>{E(!0)};async function M(){if(m(!0),!r||!o)return;const T=Bs(l),B=JSON.stringify(T),z={...o,template:B,filterValues:p};await Ss(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),m(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(da,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Ra,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(La,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:D,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:M,size:"sm",children:e.jsx(Mt,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(en,{isOpen:h,onClose:()=>f(!1)})]})]})}function Mr({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ue.useRef(null),[h,f]=ue.useState(!1),[p,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{m.current&&g(m.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,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:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:p},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(It,{className:s.cn("size-3.5 opacity-50",o&&"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(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(ba,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ya,{className:"size-4"});if(t==="Table")return e.jsx(cs,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function p(){return e.jsxs(s.Select,{disabled:u,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",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"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(It,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function g(){return e.jsx(Mr,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?p():g()})})}function Ar({column:t}){const[a,n]=A.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function p(x,v){var R;const j=s.createSqlGenConfig(x,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;m(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(h(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,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:g()})]})}function Vs({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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($e,{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(es,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Qn,{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 ps({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Vs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Lr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Rr({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ps,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(ps,{column:a})}),e.jsx(Lr,{id:a.column_name,type:"column",children:e.jsx(ps,{column:a})})]})}const fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"groupby",type:"string"},js={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},sn={id:"__placeholder__"},Te="droppable-group-by",Ie="droppable-metrics",Me="droppable-pivot-by",ts="sortable-group-by",ws="sortable-metrics",ns="sortable-pivot-by",Ds="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Or(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var B;const{active:y,over:T}=I;if(((B=y.data.current)==null?void 0:B.type)==="column"&&T){const z=T.id,V=j.find(_=>_.column_name===y.id);if(!V)return;const P=s.isNumberDataType(V.data_type),X=s.isTextDataType(V.data_type),K=s.isDateDataType(V.data_type);if(X||K){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==fs.id);q.splice($,0,fs),d(q)}else if(T.id===Te){c(a.length);const $=[...a,fs];d($),u(n),m(r)}}if(X||K){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==gs.id);q.splice($,0,gs),h(q)}else if(T.id===Me){c(l.length);const $=[...l,gs];h($),d(a),u(n),m(r)}}if(P||X){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==js.id);q.splice($,0,js),u(q)}else if(T.id===Ie){c(n.length);const $=[...n,js];u($),m(r),d(a),h(l)}}if(S(V)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==ys.id);q.splice($,0,ys),m(q)}else if(T.id===Ds){c(r.length);const $=[...r,ys];m($),u(n),d(a),h(l)}}}else d(a),u(n),m(r),h(l)};function E(I){i(I.active.id),c(null),d(a),u(n),m(r),h(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:B}=I,z=[...n],V=t!==null?t:n.length,P={...I,id:fe(T),name:T,label:He(T,y),type:B,role:"metric",aggregate:y};z.splice(V,0,P),p(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],B=t!==null?t:l.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],B=t!==null?t:a.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,B={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,B),g(y)}function D(I){var z,V,P,X,K,_,$,q;const{active:y,over:T}=I,B=y.data.current;if((B==null?void 0:B.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const G=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),Y=s.isDateDataType(U.data_type);(Q||Y)&&(T.id===Te||((z=T.data.current)==null?void 0:z.type)===ts)&&w(U),(Q||Y)&&(T.id===Me||((V=T.data.current)==null?void 0:V.type)===ns)?k(U):(G||Q)&&(T.id===Ie||((P=T.data.current)==null?void 0:P.type)===ws)?(G&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===Ds||((X=T.data.current)==null?void 0:X.type)===ks)&&L(U)}if(T&&((K=T.data.current)==null?void 0:K.type)===ts&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),G=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...a],[Y]=Q.splice(U,1);Q.splice(G,0,Y),f(Q)}}if(T&&((_=T.data.current)==null?void 0:_.type)===ns&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),G=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...l],[Y]=Q.splice(U,1);Q.splice(G,0,Y),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===ws&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),G=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...n],[Y]=Q.splice(U,1);Q.splice(G,0,Y),p(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),G=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...r],[Y]=Q.splice(U,1);Q.splice(G,0,Y),g(Q)}}O(I),i(null),c(null),d(a),u(n),m(r),h(l)}function O(I){const{active:y,over:T}=I,B=y.data.current;if((B==null?void 0:B.type)===_s&&T){const z=o.findIndex(P=>Ue(P.columnId)===y.id),V=o.findIndex(P=>Ue(P.columnId)===T.id);if(z!==-1&&V!==-1&&z!==V){const P=[...o],[X]=P.splice(z,1);P.splice(V,0,X),x(P)}}}function M(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:E,handleDragCancel:M,sensors:C}}function fe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ue(t){return`${_s}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Fr({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.metricColumns});s.useEditorStore(y=>{var T,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),m=s.useEditorStore(y=>y.selectedTableName),h=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function k(y){var T;if(l){const B=s.createSqlGenConfig(y,o);C(B);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,V=s.getSql(B,s.fmt(t),s.fmt(a),z||"",E,d||"");V&&(j(V),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type};v(B)}else{const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(B)}if(s.isDateDataType(y.data_type)){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(B)}if(s.isNumberDataType(y.data_type)){const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(B)}}}function w(y){y===!0&&(m||N)&&c?(p({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function D(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===m||y.datamodelName===N)))!==void 0}function M(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Vs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Rr,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(pa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:D,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:M(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function tn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:m,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:D,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:M,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:B,refetchModels:z,refetchSchemas:V,refetchTables:P,refetchColumns:X,refetchConnections:K,handleConnectionChange:_,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:G,tableName:Q,schemaName:Y}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(Y,Q,b):e.jsx(Fr,{schemaName:Y,tableName:Q,columns:b,status:O?"Loading...":D?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),h(ne)}function H(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:B,showNone:!0,onChange:$,isError:k,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function F(){if(r&&!T&&(!c||c==="none")&&(!l||l==="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 J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:V,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function be(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:G,isError:I,items:j,isLoading:M,value:d||"",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]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:K,items:p,title:"Connection",value:r||"",onChange:_,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),H(),F(),J(),ie(),be()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="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:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ga,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function nn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const p=f.toString();navigator.clipboard.writeText(p),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!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 ${a}`,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 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&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 an({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(nn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(ca,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function rn({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{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-[600px]",children:e.jsx(an,{sql:t,error:a,onDebugWithAssistant:n})})]})}var on={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},pt=A.createContext&&A.createContext(on),Br=["attr","size","title"];function zr(t,a){if(t==null)return{};var n=Pr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Pr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function as(){return as=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},as.apply(this,arguments)}function ft(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function rs(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?ft(Object(n),!0).forEach(function(r){Vr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ft(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Vr(t,a,n){return a=_r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function _r(t){var a=Ur(t,"string");return typeof a=="symbol"?a:a+""}function Ur(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function ln(t){return t&&t.map((a,n)=>A.createElement(a.tag,rs({key:n},a.attr),ln(a.child)))}function Le(t){return a=>A.createElement($r,as({attr:rs({},t.attr)},a),ln(t.child))}function $r(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=zr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",as({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:rs(rs({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&A.createElement("title",null,l),t.children)};return pt!==void 0?A.createElement(pt.Consumer,null,n=>a(n)):a(on)}function qr(t){return Le({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 cn(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),f=r.cards.find(x=>x.id===l),p=A.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);A.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let v=h.current[l];if(!v){const j=p();v=c.editor.createModel(j,t),h.current[l]=v}m.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,p]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),A.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(x,v){if(m.current=x,!h.current[o.id]){const j=x.getModel(),b=p();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function Yr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=cn("sql");function l(c){n(c),s.isObjectEmpty(a)||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:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=cn("python");function r(o){a(o)}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:n})}function Hr({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 Us({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);zs(((c=n.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),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=Ps();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Qr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=Ps(),c=s.useSelectedVisual(),i=ar(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function $s(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}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 us(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:p,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),p(void 0),d(""),u(""),m({}),g("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 Kr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,o]=A.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var X;return(X=P==null?void 0:P.card)==null?void 0:X.sql}),d=s.useEditorStore(P=>{var X;return(X=P==null?void 0:P.card)==null?void 0:X.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:k,isFetching:w,isSuccess:L,isError:D,error:O,queryKey:M,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);A.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);h(P)}},[N,h,g]),A.useEffect(()=>{(k||w)&&S(!0),(D||L)&&S(!1),D&&(h([]),g(""))},[k,w,N,g,D,L,S,h,O]),A.useEffect(()=>{R&&(t.getQueryData(M)||I(),E(!1))},[R,I,E,M,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
407
407
 
408
408
  Error:
409
409
 
@@ -415,11 +415,11 @@
415
415
 
416
416
  ${d?`Python:
417
417
  ${d}`:""}
418
- `;b(P)}function F(){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(Hr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(qr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gr,{})}),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:D||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[D||w?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(an,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:T}),e.jsx(ds,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx($r,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!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(Us,{}),e.jsx(Vs,{})]})]})}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(),F()]}),_()]})}function Wr({data:t}){var c;const[a,n]=M.useState([]),o=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),l=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:l.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=l.getRowModel().rows)!=null&&c.length?l.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Jr({card:t}){var b,C,R,E,S,N,D,w,L,k,O;const[a,n]=M.useState(!1),[r,o]=M.useState([]),{authToken:l}=s.useSemaphorContext(),c=s.getTokenParams(l==null?void 0:l.accessToken),i=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((E=t.customCardPreferences)==null?void 0:E.url)||""),m=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:p}=s.useDashboardCardQuery(t),g=M.useCallback((A,I)=>{o(y=>({...y,[A]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=u((D=t.customCardPreferences)==null?void 0:D.componentName);function v(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(_=>_.id===I);return y||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(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(p==null?void 0:p.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function cn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,l=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===l.filterId),{data:u,isLoading:m,isFetching:h,errorMessage:f}=s.useDashboardCardQuery(n),{setCard:p}=s.useEditorActions(),{data:g}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackCustomVisual,children:e.jsx(Jr,{card:C})})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!m&&!h)return f?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(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:m||h?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)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:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>p({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>p({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>i({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const ys=({language:t,value:a,onChange:n,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:a,onChange:n}),Yr=()=>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."})]})]}),Xr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>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(ys,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{language:"javascript",value:t,onChange:o})})]}),Zr=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>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:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function eo(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(""),m=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:g}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=E=>{var S,N;return JSON.stringify({...E,data:{...E.data,datasets:(N=(S=E.data)==null?void 0:S.datasets)==null?void 0:N.map(D=>({...D,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=p==null?void 0:p.records)!=null&&S.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:g});if(E){r(j(E)),i(((N=m.preferences)==null?void 0:N.customVisualCode)||"");const D=s.merge(E,h);l(j(D))}},C=()=>{try{if(c&&v(c),o){const E=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),E);x(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"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(Yr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Xr,{customCode:c,cardCustomCfgString:f,mergedConfig:o,onConfigChange:E=>l(E??""),onCodeChange:E=>i(E??"")})]}),e.jsx(Zr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{l(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function us(t){const[a,n]=M.useState(null);return a}function $s(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function so({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:l,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=$s();function d(u,m){r(null),o({}),l(u),m&&c({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var m;if(i){const f=(await Promise.all((m=i==null?void 0:i.plugins)==null?void 0:m.map(async p=>(await s.loadManifest(p.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:p.value}))))).flat();n(f)}})()},[i]),a.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:a.map((u,m)=>e.jsx(to,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+m))})]})}const to=({text:t,icon:a,onClick:n})=>{const r=us(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function qs(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function no(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function Gs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Hs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Ks(t){return Me({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Qs(t){return Me({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function dn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:l,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){l(null),r({}),n(m),["custom","text","map"].includes(m)&&(o(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Ct,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})})]})}function ao({chartType:t,className:a,customIcon:n,componentName:r}){const o=us();switch(t){case"bar":return e.jsx(rs,{className:a});case"line":return e.jsx(os,{className:a});case"pie":return e.jsx(is,{className:a});case"radar":return e.jsx(Rs,{className:a});case"scatter":return e.jsx(As,{className:a});case"bubble":return e.jsx(Gs,{className:a});case"doughnut":return e.jsx(Ms,{className:a});case"stackedBar":return e.jsx(Ts,{className:a});case"stackedLine":return e.jsx(Ks,{className:a});case"polarArea":return e.jsx(qs,{className:a});case"funnel":return e.jsx(Hs,{className:a});case"tornado":case"pyramid":return e.jsx(Os,{className:a});case"range":return e.jsx(Is,{className:a});case"kpi":return e.jsx(Qs,{className:a});case"text":return e.jsx(Ge,{className:a});case"map":return e.jsx(Ls,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx($e,{className:a});default:return e.jsx(ls,{className:a})}}function un({variant:t="ghost"}){var l,c;const[a,n]=M.useState(!1),r=s.useEditorStore(i=>i.card),o=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(ao,{className:"size-4",chartType:o,customIcon:(l=r.customCardPreferences)==null?void 0:l.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(dn,{onChartTypeChange:()=>n(!1)}),e.jsx(so,{onChartTypeChange:()=>n(!1)})]})]})}const Ke="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function ft(t,a){var r,o,l;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((l=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:l.type)||"linear"}function ro(){var T,F,z,_,P,Y;const[t,a]=M.useState(!1),n=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.preferences}),r=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.type}),o=s.getNumberAxis(n,{}),[l,c]=M.useState(ft(n,r)),[i,d]=M.useState(((z=(F=(T=n==null?void 0:n.chartOptions)==null?void 0:T.scales)==null?void 0:F[o])==null?void 0:z.min)||""),[u,m]=M.useState(((Y=(P=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:P[o])==null?void 0:Y.max)||""),[h,f]=M.useState(i||u?"custom":"auto"),[p,g]=M.useState(""),[x,v]=M.useState(0),[j,b]=M.useState(""),[C,R]=M.useState(""),[E,S]=M.useState(""),N=s.useEditorStore(W=>W.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),w=s.useEditorStore(W=>W.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var W,V,$,q,U,H,Q,G,Z,te,ae,se,oe,K;c(ft(n,r)),d((($=(V=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:V[o])==null?void 0:$.min)===0?0:""),m(((H=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:H.max)||""),g(((te=(Z=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,o,r]);function k(W,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(W)}function O(){const W=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>R(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),W.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:E,onValueChange:V=>S(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>v(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ke}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:l,onValueChange:W=>c(W),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),l=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:h,onValueChange:W=>f(W),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&l=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:W=>d(V=>k(V,W.target.value)),className:`col-span-1 h-8 w-full ${Ke}`}),e.jsx(s.Input,{value:u,onChange:W=>m(V=>k(V,W.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ke}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:p,onChange:W=>g(V=>k(V,W.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ke}`})]})]})}function y(){var q;let W={};h==="custom"&&(W={min:i,max:u,ticks:{stepSize:p}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:l,...l==="linear"?W:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:E}};console.log(V),N(V);const $={...w,preferences:V};D($)}return e.jsxs(s.Popover,{onOpenChange:W=>a(W),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(Zn,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function oo(){const t=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.position}),a=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.align}),n=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.display}),{setLegendOptions:r}=s.useEditorActions(),o=i=>{r({display:i,position:t,align:a})},l=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(da,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>l("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>l("left"),children:e.jsx(_n,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>l("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>l("right"),children:e.jsx(Vn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(On,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Rn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Bn,{className:"size-4"})})]})]})]})]})]})})]})}function io(){const t=s.useEditorStore(l=>{var c,i;return(i=(c=l.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(l=>l.card.type),{setChartOrientation:n}=s.useEditorStore(l=>l.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function mn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function l(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?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(io,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ro,{}),e.jsx(oo,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(r==="xy"||!r)&&e.jsx(ia,{className:"size-4"}),r==="x"&&e.jsx(Jn,{className:"size-4"}),r==="y"&&e.jsx(ba,{className:"size-4"}),r==="none"&&e.jsx(ka,{className:"size-4"})]})]}):null}function lo(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:l}=s.useEditorActions(),c=(g,x)=>{g.dataTransfer.setData("tabIndex",x.toString())},i=g=>{g.preventDefault()},d=(g,x)=>{const v=g.dataTransfer.getData("tabIndex");if(v===x.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(x,0,b),n({...t,cards:j})};function u(g){const x=t.cards.filter(b=>b.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function m(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function h(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,g)}function f(g){const x={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(g,x)}function p(g,x){return g.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||g.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:v}),l({...x,displayTab:v})},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(ea,{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((g,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,x),onDragOver:i,onDrop:v=>d(v,x),className:"",value:g.id,children:[p(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),l({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),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(Xn,{className:"h-4 w-4"})})]})})}function hn(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:l,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(a);function f(x){const v=t.cards.find(j=>j.id===x);if(v!=null&&v.sql){r||i(!0),l(x);return}if(v!=null&&v.queryConfig){r&&i(!1),p(x),l(x);return}r||p(x),l(x)}function p(x){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};o(v);const j=v.cards.find(b=>b.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?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.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m})})}):a.type==="text"?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:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,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:g()},x.id)),e.jsx(lo,{})]})}function Qe({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),l=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m}=s.useEditorActions(),{data:h,isLoading:f,isFetching:p,errorMessage:g}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(h==null?void 0:h.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),E=document.createElement("a");E.href=R,E.download=`${a.title}.json`,E.click()}function v(){const C=[Object.keys(h==null?void 0:h.records.reduce((N,D)=>({...N,...D}),{})).join(","),...((h==null?void 0:h.records)||[]).map(N=>Object.values(N).join(","))].join(`
419
- `),R=new Blob([C],{type:"text/csv"}),E=URL.createObjectURL(R),S=document.createElement("a");S.href=E,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(f||p)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(un,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Gn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(eo,{})]}),!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:v,children:e.jsx(no,{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:x,children:e.jsx(ta,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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(mn,{})]}),n&&e.jsx(uo,{})]}),r?e.jsx(hn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&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:l&&e.jsx(co,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(Wr,{data:(h==null?void 0:h.records)||[]}),g&&e.jsx(tn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function co(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function uo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.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:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function mo(){var x,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=$s(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function m(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function h(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(E=>{var S;return((S=E==null?void 0:E.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((E,S)=>{var N,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((D=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:D.cardId)||"",onValueChange:w=>m(S,w)})]},S+Math.random())})})}function f(j,b,C=[],R=""){var E,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function p(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,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(he,{icon:e.jsx(qn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:g,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(he,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(j=>j.type===l).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Le(){const[t,a]=M.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),M.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function c(u,m){var h,f;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(p=>p.columnIndex!==u)}),a(p=>{const g=[...p];return g[u]=!1,g}))}function i(u,m){var f;const h=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);o({...n,onClickFilter:h})}function d(u){var m,h,f,p;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(g=>g.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(p=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))==null?void 0:p.expression,onChange:g=>i(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),l==null?void 0:l.map((u,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const g=[...p];return g[m]=!p[m],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})]})}function ho({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,l=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...l};h.datalabels=m;const f=n==null?void 0:n.map(p=>p.idx===u?h:p);r({...a,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Mt,{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(ua,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ha,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ma,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function xo(){const t=s.useEditorStore(l=>l.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ws({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function xn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=xo();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:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:pn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(fn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function pn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function fn({col:t,idx:a,className:n,iconClassName:r,children:o}){const l=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...l,datasetOptions:[...c||[],{idx:a,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 f=c==null?void 0:c.map(p=>p.idx===a?h:p);d({...l,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ws,{className:"max-w-[100px]",title:t,children:pn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(rs,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(os,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(wt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ho,{idx:a})]})]})}function gn(){const t=s.useEditorStore(p=>p.selectedConnectionId),a=s.useEditorStore(p=>p.selectedDatamodelId),n=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedTableName),l=s.useDashboardStore(p=>p.dashboard.filters)||[],c=s.useDashboardStore(p=>p.actions.addFilter),i=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function f(p,g="dashboard"){var N;const x=s.fmt(p.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(m);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:h,databaseName:v}),R=`${C}.${x}`;const E=(N=u==null?void 0:u.find(D=>D.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${E}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${E}`);const S=l==null?void 0:l.find(D=>D.column===R&&D.table===b&&(D.database===v||D.database===n));if(S)d(S.id),i(S.id);else{const D=s.v4();return m==="api"&&t?(c({location:g,id:D,column:R,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),D):(c({id:D,location:g,column:R,title:p.column_name,dataType:p.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),D)}}return{assignFilter:f}}function _e(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();function l(i){const d=o(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(po,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function po({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,l]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==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:d=>{const u=d===o?"":d;l(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function fo({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:a=>a.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(xn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function ms(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,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,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,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:a?l():c()})}function go({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="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"}),n==="bubble"&&e.jsx("li",{children:"radius - 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/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:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(ms,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}const jo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},yo={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function vo(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:bo(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ms,{}),e.jsx(Le,{}),e.jsx(_e,{})]})]})}function bo(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(jo,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(yo,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 No(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function vs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Co=[{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"}],So=["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"],wo=So.map(t=>({label:t,value:t}));function ko(){var d,u,m,h,f,p,g,x,v,j,b,C,R,E,S,N,D,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=M.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(L=>({label:L,value:L}))||[],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(vs,{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(vs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((p=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Co,value:((x=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:wo,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(vs,{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:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionScale:Number(L.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=(E=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(D=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Do(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,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 We({cardType:t,docContent:a,suffix:n="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)} ${n}`}),e.jsx(s.AccordionContent,{children:a||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:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,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:[t!=="text"&&e.jsx(ms,{}),t==="text"&&e.jsx(Do,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Eo(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(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:[n(),e.jsx(xn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function To({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})}),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"})]})]})}const Io=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."]})]}),Ao=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."]})]}),Mo=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 Lo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Eo,{});case"tornado":case"pyramid":return e.jsx(We,{docContent:Io,cardType:n});case"kpi":return e.jsx(No,{});case"line":case"bar":return e.jsx(fo,{cardType:n});case"range":return e.jsx(We,{docContent:Ao,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(We,{cardType:n});case"bubble":case"scatter":return e.jsx(go,{cardType:n});case"table":return e.jsx(To,{cardType:n});case"text":return e.jsx(We,{docContent:Mo,cardType:n,suffix:"Visual"});case"map":return e.jsx(ko,{});case"custom":return e.jsx(mo,{});default:return e.jsx(vo,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function jn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function l(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Ro=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ue,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Pn,{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 Oo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Ro;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};a(t.id,l)}return e.jsx(jn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Bo=[{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 Fo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:Pe(t.name,r)};a(t.id,o)}return e.jsx(jn,{column:t,functions:Bo,onFunctionChange:r=>n(r),label:"Granularity"})}function zo({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=M.useMemo(()=>{let i=[];(n===Ee||n===Te||n===Ie)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,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 yn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(fn,{idx:l,col:o,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(ms,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Po({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,l]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),x=f?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(f),transition:p}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),D=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":D?"string":w?"date":"string";if(r===Ee){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,role:"groupby",label:Pe(S.column_name,"month"),granularity:"month"};c(t.id,k)}}if(r===Ie){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,label:Pe(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,k)}}if(r===Te){const k={id:t.id,name:S.column_name,type:L,role:"metric",label:He(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};i(t.id,k)}}function b(){if(r===Te)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(yn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Te)return e.jsx(Oo,{column:t});if((r===Ee||r===Ie)&&S)return e.jsx(Fo,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ee||r===Ie)&&v}),children:e.jsx(zo,{col:t,onChange:j,droppableId:r})})}function E(){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:()=>l(!o),children:o?e.jsx(Sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Dt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,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:[E(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function bs({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:l}){var x,v;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),m=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),h=i||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,f=u?r:n,p=o===ss?"Rows":o===ts?"Pivot Columns":"Columns";function g(){if(!f||f.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:n==null?void 0:n.map(j=>j.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:a}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:p})]}),g(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(j=>j.id===en.id?e.jsx(_o,{},j.id):e.jsx(Po,{droppableId:t,type:o,column:j,onRemoveColumn:l},j.id))})]})})}function _o(){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 vn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function Vo(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function f(j,b){const C=p(j);return C?C.role==="metric"?b==="asc"?u:m:b==="asc"?i:d:null}function p(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};l(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>Ve(j.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:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(vn,{id:Ve(j.columnId),type:_s,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(Dt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ws,{className:"w-[175px] text-sm",children:((b=p(j.columnId))==null?void 0:b.label)||((C=p(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:f(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.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"})})})]})},j.columnId)},Ve(j.columnId))})]})})}function Uo(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),l=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(v){i(v)}function h(v){d(v)}function f(v){u(v)}let p="Group By",g="Metrics",x="Stack By";return a==="table"&&(p="Rows",g="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(dn,{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(bs,{onRemoveColumn:m,sortableType:ss,id:Ee,label:p,columns:t,previewColumns:n}),e.jsx(bs,{onRemoveColumn:f,sortableType:ts,id:Ie,label:x,columns:l,previewColumns:c}),e.jsx(bs,{onRemoveColumn:h,sortableType:Ss,id:Te,label:g,columns:r,previewColumns:o}),e.jsx(Vo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Js({children:t,column:a,id:n,sortableType:r,className:o}){const[l,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var f,p;return(p=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:p.some(g=>g.filterColumnName===a.name)});function m(h){i(h)}return e.jsx(vn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),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:a.name}),u&&e.jsx("button",{onClick:()=>d(a),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(a),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",!l&&"rounded-b-md",l&&"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",o),children:t})]})]})})}function $o({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,E;return(E=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:E.filters}),o=s.useEditorStore(C=>{var R,E;return(E=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:E.find(S=>S.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:f,isLoading:p,isFetching:g,isError:x}=s.useFilterQuery(h),v=M.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(E=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return E[S]===void 0&&(S=S.toLowerCase()),{id:E[S],value:E[S]}}):[]},[f,h.column]);function j(C){const R=C.map(E=>E.id);m(t.name,R)}function b(){return p||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.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(qo,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Js,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function qo({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Go({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:p,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const E={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,E)}function b(){v(t.name,null,!0),g(x)}function C(){return d||u?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"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:p,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Js,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Ho({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,x;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},m=c||((x=(g=i==null?void 0:i.data)==null?void 0:g.current)==null?void 0:x.type)===o;function h(){if(!p||p.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 f(v){const j=s.isDateDataType(v.type);return v.id===en.id?e.jsx(Js,{id:v.id,sortableType:o,column:v,children:e.jsx(Ko,{})},v.id):j?e.jsx(Go,{droppableId:t,sortableType:o,column:v},v.id):e.jsx($o,{droppableId:t,sortableType:o,column:v},v.id)}const p=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.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:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:p==null?void 0:p.map(v=>f(v))})]})})}function Ko(){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 Qo(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Ho,{onRemoveColumn:r,sortableType:ks,id:ws,label:"Filters",columns:t,previewColumns:a})})}function Wo(){const t=s.useEditorStore(l=>l.card),a=s.useEditorStore(l=>l.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage: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(ds,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(an,{sql:r==null?void 0:r.sql,error: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(Us,{}),e.jsx(Vs,{variant:"default"})]})]})}function Jo(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=a.current)==null||m.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Lo,{})})}),!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:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Uo,{})})}),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(Wo,{}),e.jsx(Qo,{})]}),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:o?l():c()})}function Yo(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[o,l]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.sql}),d=s.useEditorStore(B=>B.isDevMode),u=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.python}),{setCardPython:m,setCardSql:h,setRunSql:f,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],v=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),R=s.useEditorStore(B=>B.selectedTableName),E=s.useEditorStore(B=>B.selectedConnectionId),S=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:D,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:k,setCurrentAssitantScope:O,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:T}=s.useEditorAside(),{messages:F,setMessages:z,reload:_,error:P,append:Y,input:W,setInput:V,status:$,handleInputChange:q,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:Q,onFinish(B,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&v&&(Y({role:"user",content:v}),k(!1))},[j,v,Y,k]);async function Q({toolCall:B}){var J,ie,ye,ke;if(["createChartFromSql","createForecast"].includes(B.toolName)){const ne=B.args.sql,le=B.args.python,ce=B.args.chartType;return p(ce),h(ne),m(le),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:u||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const ne=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,p(ne),A(le),h(void 0),m(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(ye=ce==null?void 0:ce.data)!=null&&ye.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(ke=ce==null?void 0:ce.data)==null?void 0:ke.records}}else r("Analyzing...")}}function G(B){l(J=>J?{promptTokens:J.promptTokens+B.promptTokens,completionTokens:J.completionTokens+B.completionTokens,totalTokens:J.totalTokens+B.totalTokens}:B)}function Z(B){const J=s.removeFromScopeArray(x,B);te(J)}function te(B){const J=s.sanitizeAIScope(B);O(J),z(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:T||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||""},J=s.dedup([...x,B]);te(J)}function se(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||"",datamodelId:T||""};if(!s.isInAiScopeArray([...N||[],...x],B)||x.length===0){const ie=s.dedup([...N||[],...x,B]).filter(ye=>ye.connectionId===B.connectionId);te(ie)}}const oe=!["ready","error"].includes($),K=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:_,append:Y,input:W,setInput:V,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:H,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:K}}const Xo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function gt(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[o,l]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,u]=M.useState(!1),m=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),f=s.useDashboardStore(H=>H.dashboard.aiContext),p=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),v=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:D,append:w,input:L,setInput:k,isLoading:O,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:T,llmUsage:F,errorMessage:z}=Yo();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),M.useEffect(()=>{var H;v&&((H=a.current)==null||H.focus(),h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[v,p,h]);function _(H,Q){Q==="sql"?(g(H),x(!0)):Q==="python"&&(C(H),x(!0))}function P(){var H;(H=f==null?void 0:f.selectedEntities)==null||H[0],u(!0)}function Y(){m.selectedEntities.length===0&&h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function W(H){Y();const Q={role:"user",content:H.title+" "+H.subtitle};w(Q)}function V(H){Y(),w({role:"user",content:H})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.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:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:T,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!E&&e.jsx(s.Placeholders,{onClick:W,placeholders:Xo}),e.jsx("div",{children:U&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:k,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Y(),I(H)},isLoading:O,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:d,onOpenChange:u,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function bn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const l=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return l===t&&c===a||l===a&&c===t})}function Zo(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!bn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function Ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Es(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Ys=t=>{var k;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,f=M.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),p=M.useCallback((O,A)=>{if(h)switch(O){case"groupBy":{a(h,{groupByColumns:A});break}case"metrics":{a(h,{metricColumns:A});break}case"pivotBy":{a(h,{pivotByColumns:A});break}case"sortBy":{a(h,{sortByColumns:A});break}}},[h,a]),g=M.useCallback((O,A,I)=>{if(!h)return;const T=f(O)[A];if(T)switch(O){case"groupBy":n(h,T.id,{label:I});break;case"metrics":r(h,T.id,{label:I});break;case"pivotBy":o(h,T.id,{label:I});break;case"sortBy":l(h,T.id,{label:I});break}},[h,f,n,r,o,l]),x=M.useCallback((O,A)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aggregate:A,label:s.getAggregationLabel(y.name,A)})},[h,f,r]),v=M.useCallback((O,A,I)=>{if(!h)return;const T=f("groupBy")[O];if(!T)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(h,T.id,F)},[h,f,n]),j=M.useCallback((O,A)=>{if(!h)return;const y=f("groupBy")[O];y&&n(h,y.id,{granularity:A})},[h,f,n]),b=M.useCallback((O,A)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aliasTemplate:A})},[h,f,r]),C=M.useCallback((O,A)=>{if(console.log("handleValueAliasesChange",O,A),!h)return;console.log("handleValueAliasesChange",O,A);const y=f("metrics")[O];y&&(console.log("handleValueAliasesChange",A),r(h,y.id,{valueAliases:A}))},[h,f,r]),R=M.useCallback(O=>{h&&a(h,{comparisonType:O})},[h,a]),E=M.useCallback(O=>{h&&a(h,{showTrendline:O})},[h,a]),S=M.useCallback(O=>{h&&a(h,{trendlineWindow:O})},[h,a]),N=M.useCallback(O=>{h&&a(h,{trendlineGranularity:O})},[h,a]),D=M.useCallback(O=>{h&&a(h,{targetValue:O})},[h,a]),w=M.useCallback(O=>{var _;if(!h)return;const A=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=Zo(O,A,I);if(!y.isValid){y.showError&&Ds();return}const T=s.getSmartContainerForField(O),F=f(T);if(Es(O,F))return;const z=s.getNewField(O,T);z&&p(T,[...F,z])},[h,(k=t==null?void 0:t.config)==null?void 0:k.joinPlan,f,p]),L=M.useCallback((O,A)=>{if(!h)return;const y=f(O)[A];if(y){if(O!=="sortBy"){const T=f("sortBy"),F=T.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==T.length&&a(h,{sortByColumns:F})}switch(O){case"groupBy":c(h,y.id);break;case"metrics":i(h,y.id);break;case"pivotBy":d(h,y.id);break;case"sortBy":u(h,y.id);break}}},[h,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:p,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:D,cardType:m}};function ei({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 si({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),u=s.useEditorStore(g=>g.card),{handleFieldClick:m}=Ys(u),h={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const f=g=>{const x=(g||"").toLowerCase();switch(s.getDataType(x)){case"number":return Ue;case"date":return s.Calendar;case"boolean":return Ze;case"json":return rt;case"geo":return ot;default:return Ge}},p=g=>{const x=(g||"").toLowerCase(),v=s.getDataType(x);return v==="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(Ge,{className:"h-3 w-3"})}):v==="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(Ue,{className:"h-3 w-3"})}):v==="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"})}):v==="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(Ze,{className:"h-3 w-3"})}):v==="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(rt,{className:"h-3 w-3"})}):v==="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(ot,{className:"h-3 w-3"})}):v==="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(St,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,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:[p(t.dataType),e.jsx(s.TooltipProvider$1,{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(ei,{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(Mt,{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(Da,{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 ti(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(C=>m(C)===n)).reduce((C,R)=>{const E=R.qualifiedEntityName||"Other Fields";return C[E]||(C[E]={label:s.toLabel(R.entityName),fields:[]}),C[E].fields.push(R),C},{}),g=Object.keys(f),x=u.filter(C=>m(C)==="dimensions").length,v=u.filter(C=>m(C)==="metrics").length,j=u.filter(C=>m(C)==="calculated").length,b=u.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?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:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.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:[l.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:C=>a(C.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),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:u.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:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(St,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(f).map(([C,R])=>{const E=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,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",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:E.label||E.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(S=>e.jsx(si,{field:S},S.id))})})]},C)})}),Object.keys(f).length===0&&l.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(f).length===0&&l.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 ni(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ti,{})," "]})}function ai({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[o,l]=M.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,N={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({...n,joins:[...n.joins,N]}),l(new Set([...o,N.id]))},i=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),l(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var k,O;const D=n.joins.find(A=>A.id===S);if(!D)return;const w={...D,...N},L=n.joins.map(A=>A.id===S?w:A);if((k=w.source)!=null&&k.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},T=[...w.joinKeyGroups];T[0]={...T[0],keys:[y]},w.joinKeyGroups=T,L[L.findIndex(F=>F.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N>0){const D=[...n.joins],w={...D[N]},L={...D[N-1]};D[N]=L,D[N-1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},moveJoinDown:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N<n.joins.length-1){const D=[...n.joins],w={...D[N]},L={...D[N+1]};D[N]=L,D[N+1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),l(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{D.add(w.source.name),D.add(w.target.name)}),a.filter(w=>D.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const D=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:D})},updateGroupOperator:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:D},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const D=n.joins.find(L=>L.id===S);if(!D)return;const w=[...D.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const D=n.joins.find(A=>A.id===S);if(!D)return;const w=a.find(A=>A.name===D.source.name),L=a.find(A=>A.name===D.target.name),k=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",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:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};k[N]={...k[N],keys:[...k[N].keys,O]},d(S,{joinKeyGroups:k})},updateJoinKey:(S,N,D,w,L)=>{const k=n.joins.find(T=>T.id===S);if(!k)return;const O=a.find(T=>T.name===k.source.name),A=a.find(T=>T.name===k.target.name),I=[...k.joinKeyGroups],y=I[N].keys[D];w==="sourceColumnName"&&O?I[N].keys[D]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[N].keys[D]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[D]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(D,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
420
- FROM ${N.name}`;return S.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const k=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var T,F,z,_;return((T=y.source)==null?void 0:T.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),O=k.length>1?k.join(" OR "):k[0]||"condition_here";D+=`
418
+ `;b(P)}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(Hr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Yr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){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:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?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(rn,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:T}),e.jsx(us,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx(qr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!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($s,{}),e.jsx(Us,{})]})]})}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()]}),V()]})}function Wr({data:t}){var c;const[a,n]=A.useState([]),o=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),l=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:l.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=l.getRowModel().rows)!=null&&c.length?l.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Jr({card:t}){var b,C,R,E,S,N,k,w,L,D,O;const[a,n]=A.useState(!1),[r,o]=A.useState([]),{authToken:l}=s.useSemaphorContext(),c=s.getTokenParams(l==null?void 0:l.accessToken),i=s.useDashboardStore(M=>M.themeStyle),d={colors:((C=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((E=t.customCardPreferences)==null?void 0:E.url)||""),m=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(M=>M.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:p}=s.useDashboardCardQuery(t),g=A.useCallback((M,I)=>{o(y=>({...y,[M]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=u((k=t.customCardPreferences)==null?void 0:k.componentName);function v(M){n(M)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(M=>{var T,B,z;const I=(B=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:B[M].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(V=>V.id===I);return y||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:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(p==null?void 0:p.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((D=t.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(M=>{var T,B,z;const I=(B=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:B[M].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(V=>V.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:M,card:y},y.id+M)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(M=>{var I;return(I=M==null?void 0:M.customCardPreferences)==null?void 0:I.settings}),data:j.map(M=>M!=null&&M.id?r==null?void 0:r[M.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function dn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,l=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===l.filterId),{data:u,isLoading:m,isFetching:h,errorMessage:f}=s.useDashboardCardQuery(n),{setCard:p}=s.useEditorActions(),{data:g}=s.useTopoJson(n),x=A.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackCustomVisual,children:e.jsx(Jr,{card:C})})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!m&&!h)return f?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(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:m||h?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)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:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>p({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>p({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>i({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const vs=({language:t,value:a,onChange:n,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:a,onChange:n}),Xr=()=>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."})]})]}),Zr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>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(vs,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(vs,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(vs,{language:"javascript",value:t,onChange:o})})]}),eo=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>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:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function so(){const[t,a]=A.useState(!1),[n,r]=A.useState(""),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:g}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=E=>{var S,N;return JSON.stringify({...E,data:{...E.data,datasets:(N=(S=E.data)==null?void 0:S.datasets)==null?void 0:N.map(k=>({...k,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=p==null?void 0:p.records)!=null&&S.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:g});if(E){r(j(E)),i(((N=m.preferences)==null?void 0:N.customVisualCode)||"");const k=s.merge(E,h);l(j(k))}},C=()=>{try{if(c&&v(c),o){const E=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),E);x(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"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(Xr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(dn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Zr,{customCode:c,cardCustomCfgString:f,mergedConfig:o,onConfigChange:E=>l(E??""),onCodeChange:E=>i(E??"")})]}),e.jsx(eo,{error:d,hasCardCustomConfig:!!h,onReset:()=>{l(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function ms(t){const[a,n]=A.useState(null);return a}function qs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function to({onChartTypeChange:t}){const[a,n]=A.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:l,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=qs();function d(u,m){r(null),o({}),l(u),m&&c({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()}return A.useEffect(()=>{(async()=>{var m;if(i){const f=(await Promise.all((m=i==null?void 0:i.plugins)==null?void 0:m.map(async p=>(await s.loadManifest(p.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:p.value}))))).flat();n(f)}})()},[i]),a.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:a.map((u,m)=>e.jsx(no,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+m))})]})}const no=({text:t,icon:a,onClick:n})=>{const r=ms(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function Ys(t){return Le({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function ao(t){return Le({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function Gs(t){return Le({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Hs(t){return Le({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Qs(t){return Le({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Ks(t){return Le({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function un({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:l,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){l(null),r({}),n(m),["custom","text","map"].includes(m)&&(o(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(cs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Qs,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Ys,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Fs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(St,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(qe,{className:s.cn("size-5",a)})})]})}function ro({chartType:t,className:a,customIcon:n,componentName:r}){const o=ms();switch(t){case"bar":return e.jsx(os,{className:a});case"line":return e.jsx(is,{className:a});case"pie":return e.jsx(ls,{className:a});case"radar":return e.jsx(Os,{className:a});case"scatter":return e.jsx(As,{className:a});case"bubble":return e.jsx(Gs,{className:a});case"doughnut":return e.jsx(Ls,{className:a});case"stackedBar":return e.jsx(Is,{className:a});case"stackedLine":return e.jsx(Qs,{className:a});case"polarArea":return e.jsx(Ys,{className:a});case"funnel":return e.jsx(Hs,{className:a});case"tornado":case"pyramid":return e.jsx(Fs,{className:a});case"range":return e.jsx(Ms,{className:a});case"kpi":return e.jsx(Ks,{className:a});case"text":return e.jsx(Ge,{className:a});case"map":return e.jsx(Rs,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(qe,{className:a});default:return e.jsx(cs,{className:a})}}function mn({variant:t="ghost"}){var l,c;const[a,n]=A.useState(!1),r=s.useEditorStore(i=>i.card),o=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(ro,{className:"size-4",chartType:o,customIcon:(l=r.customCardPreferences)==null?void 0:l.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(un,{onChartTypeChange:()=>n(!1)}),e.jsx(to,{onChartTypeChange:()=>n(!1)})]})]})}const Qe="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function gt(t,a){var r,o,l;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((l=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:l.type)||"linear"}function oo(){var T,B,z,V,P,X;const[t,a]=A.useState(!1),n=s.useEditorStore(K=>{var _;return(_=K.card)==null?void 0:_.preferences}),r=s.useEditorStore(K=>{var _;return(_=K.card)==null?void 0:_.type}),o=s.getNumberAxis(n,{}),[l,c]=A.useState(gt(n,r)),[i,d]=A.useState(((z=(B=(T=n==null?void 0:n.chartOptions)==null?void 0:T.scales)==null?void 0:B[o])==null?void 0:z.min)||""),[u,m]=A.useState(((X=(P=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:P[o])==null?void 0:X.max)||""),[h,f]=A.useState(i||u?"custom":"auto"),[p,g]=A.useState(""),[x,v]=A.useState(0),[j,b]=A.useState(""),[C,R]=A.useState(""),[E,S]=A.useState(""),N=s.useEditorStore(K=>K.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(K=>K.card),L=["pie","doughnut","polarArea","funnel"].includes(r);A.useEffect(()=>{var K,_,$,q,U,G,Q,Y,Z,te,ae,se,oe,H;c(gt(n,r)),d((($=(_=(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales)==null?void 0:_[o])==null?void 0:$.min)===0?0:""),m(((G=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:G.max)||""),g(((te=(Z=(Y=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:Y[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((H=n==null?void 0:n.numberAxisFormat)==null?void 0:H.locale)||"")},[t,n,o,r]);function D(K,_){return _===""||/^[0-9\b]+$/.test(_)?Number(_):Number(K)}function O(){const K=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(_=>_.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:_=>R(_==="none"?"":_),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),K.map(_=>e.jsx(s.SelectItem,{value:_,children:_},_))]})})]}),e.jsxs(s.Select,{value:E,onValueChange:_=>S(_),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(_=>e.jsx(s.SelectItem,{value:_.locale,children:_.locale},_.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:_=>v(Number(_.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Qe}`})]})]})}function M(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:l,onValueChange:K=>c(K),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),l=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:h,onValueChange:K=>f(K),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&l=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:K=>d(_=>D(_,K.target.value)),className:`col-span-1 h-8 w-full ${Qe}`}),e.jsx(s.Input,{value:u,onChange:K=>m(_=>D(_,K.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Qe}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:p,onChange:K=>g(_=>D(_,K.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Qe}`})]})]})}function y(){var q;let K={};h==="custom"&&(K={min:i,max:u,ticks:{stepSize:p}});const _={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:l,...l==="linear"?K:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:E}};console.log(_),N(_);const $={...w,preferences:_};k($)}return e.jsxs(s.Popover,{onOpenChange:K=>a(K),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(ea,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),M(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function io(){const t=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.position}),a=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.align}),n=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.display}),{setLegendOptions:r}=s.useEditorActions(),o=i=>{r({display:i,position:t,align:a})},l=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(ua,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>l("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>l("left"),children:e.jsx(_n,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>l("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>l("right"),children:e.jsx(Un,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(Fn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(On,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Bn,{className:"size-4"})})]})]})]})]})]})})]})}function lo(){const t=s.useEditorStore(l=>{var c,i;return(i=(c=l.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(l=>l.card.type),{setChartOrientation:n}=s.useEditorStore(l=>l.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(ct,{className:"size-4"}):e.jsx(lt,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(ct,{className:"size-4"}):e.jsx(lt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function hn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function l(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?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(lo,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(oo,{}),e.jsx(io,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(r==="xy"||!r)&&e.jsx(la,{className:"size-4"}),r==="x"&&e.jsx(Jn,{className:"size-4"}),r==="y"&&e.jsx(Na,{className:"size-4"}),r==="none"&&e.jsx(ka,{className:"size-4"})]})]}):null}function co(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:l}=s.useEditorActions(),c=(g,x)=>{g.dataTransfer.setData("tabIndex",x.toString())},i=g=>{g.preventDefault()},d=(g,x)=>{const v=g.dataTransfer.getData("tabIndex");if(v===x.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(x,0,b),n({...t,cards:j})};function u(g){const x=t.cards.filter(b=>b.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function m(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function h(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,g)}function f(g){const x={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(g,x)}function p(g,x){return g.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||g.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:v}),l({...x,displayTab:v})},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(sa,{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((g,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,x),onDragOver:i,onDrop:v=>d(v,x),className:"",value:g.id,children:[p(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),l({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),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(Zn,{className:"h-4 w-4"})})]})})}function xn(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:l,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(a);function f(x){const v=t.cards.find(j=>j.id===x);if(v!=null&&v.sql){r||i(!0),l(x);return}if(v!=null&&v.queryConfig){r&&i(!1),p(x),l(x);return}r||p(x),l(x)}function p(x){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};o(v);const j=v.cards.find(b=>b.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?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.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m})})}):a.type==="text"?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:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(dn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,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:g()},x.id)),e.jsx(co,{})]})}function Ke({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),l=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m}=s.useEditorActions(),{data:h,isLoading:f,isFetching:p,errorMessage:g}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(h==null?void 0:h.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),E=document.createElement("a");E.href=R,E.download=`${a.title}.json`,E.click()}function v(){const C=[Object.keys(h==null?void 0:h.records.reduce((N,k)=>({...N,...k}),{})).join(","),...((h==null?void 0:h.records)||[]).map(N=>Object.values(N).join(","))].join(`
419
+ `),R=new Blob([C],{type:"text/csv"}),E=URL.createObjectURL(R),S=document.createElement("a");S.href=E,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(f||p)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(mn,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Gn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(so,{})]}),!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:v,children:e.jsx(ao,{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:x,children:e.jsx(na,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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(hn,{})]}),n&&e.jsx(mo,{})]}),r?e.jsx(xn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&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:l&&e.jsx(uo,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(Wr,{data:(h==null?void 0:h.records)||[]}),g&&e.jsx(nn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function uo(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function mo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.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:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ho(){var x,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=qs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function m(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function h(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(E=>{var S;return((S=E==null?void 0:E.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((E,S)=>{var N,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((k=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:k.cardId)||"",onValueChange:w=>m(S,w)})]},S+Math.random())})})}function f(j,b,C=[],R=""){var E,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function p(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,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(he,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:g,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(he,{icon:e.jsx(Xn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(j=>j.type===l).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Re(){const[t,a]=A.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function c(u,m){var h,f;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(p=>p.columnIndex!==u)}),a(p=>{const g=[...p];return g[u]=!1,g}))}function i(u,m){var f;const h=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);o({...n,onClickFilter:h})}function d(u){var m,h,f,p;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(g=>g.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(p=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))==null?void 0:p.expression,onChange:g=>i(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),l==null?void 0:l.map((u,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const g=[...p];return g[m]=!p[m],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})]})}function xo({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,l=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...l};h.datalabels=m;const f=n==null?void 0:n.map(p=>p.idx===u?h:p);r({...a,datasetOptions:f})}}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(ma,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(xa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ha,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function po(){const t=s.useEditorStore(l=>l.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ws({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function pn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=po();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:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:fn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(gn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function fn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function gn({col:t,idx:a,className:n,iconClassName:r,children:o}){const l=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...l,datasetOptions:[...c||[],{idx:a,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 f=c==null?void 0:c.map(p=>p.idx===a?h:p);d({...l,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ws,{className:"max-w-[100px]",title:t,children:fn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(os,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(is,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Dt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xo,{idx:a})]})]})}function jn(){const t=s.useEditorStore(p=>p.selectedConnectionId),a=s.useEditorStore(p=>p.selectedDatamodelId),n=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedTableName),l=s.useDashboardStore(p=>p.dashboard.filters)||[],c=s.useDashboardStore(p=>p.actions.addFilter),i=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function f(p,g="dashboard"){var N;const x=s.fmt(p.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(m);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:h,databaseName:v}),R=`${C}.${x}`;const E=(N=u==null?void 0:u.find(k=>k.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${E}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${E}`);const S=l==null?void 0:l.find(k=>k.column===R&&k.table===b&&(k.database===v||k.database===n));if(S)d(S.id),i(S.id);else{const k=s.v4();return m==="api"&&t?(c({location:g,id:k,column:R,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),k):(c({id:k,location:g,column:R,title:p.column_name,dataType:p.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),k)}}return{assignFilter:f}}function Ve(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();function l(i){const d=o(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(fo,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function fo({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,l]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==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:d=>{const u=d===o?"":d;l(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function go({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:a=>a.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(pn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ve,{})]})]})]})})}function hs(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,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,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,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:a?l():c()})}function jo({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="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"}),n==="bubble"&&e.jsx("li",{children:"radius - 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/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:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(hs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ve,{})]})]})]})})}const yo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},vo={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function bo(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:No(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(hs,{}),e.jsx(Re,{}),e.jsx(Ve,{})]})]})}function No(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(yo,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(vo,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 Co(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function bs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const So=[{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"}],wo=["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"],Do=wo.map(t=>({label:t,value:t}));function ko(){var d,u,m,h,f,p,g,x,v,j,b,C,R,E,S,N,k,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(L=>({label:L,value:L}))||[],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(bs,{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(bs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((p=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:So,value:((x=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Do,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(bs,{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:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionScale:Number(L.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=(E=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var D,O,M,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(M=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var D,O,M,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[((I=(M=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Re,{})]})}function Eo(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,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 We({cardType:t,docContent:a,suffix:n="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)} ${n}`}),e.jsx(s.AccordionContent,{children:a||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:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,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:[t!=="text"&&e.jsx(hs,{}),t==="text"&&e.jsx(Eo,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ve,{})]})]})]})})}function To(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(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:[n(),e.jsx(pn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ve,{})]})]})]})})}function Io({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ve,{})]})]})}),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"})]})]})}const Mo=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."]})]}),Ao=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."]})]}),Lo=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 Ro(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(To,{});case"tornado":case"pyramid":return e.jsx(We,{docContent:Mo,cardType:n});case"kpi":return e.jsx(Co,{});case"line":case"bar":return e.jsx(go,{cardType:n});case"range":return e.jsx(We,{docContent:Ao,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(We,{cardType:n});case"bubble":case"scatter":return e.jsx(jo,{cardType:n});case"table":return e.jsx(Io,{cardType:n});case"text":return e.jsx(We,{docContent:Lo,cardType:n,suffix:"Visual"});case"map":return e.jsx(ko,{});case"custom":return e.jsx(ho,{});default:return e.jsx(bo,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function yn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function l(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Oo=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx($e,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ra,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Vn,{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 Fo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Oo;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};a(t.id,l)}return e.jsx(yn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Bo=[{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 zo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:Pe(t.name,r)};a(t.id,o)}return e.jsx(yn,{column:t,functions:Bo,onFunctionChange:r=>n(r),label:"Granularity"})}function Po({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=A.useMemo(()=>{let i=[];(n===Te||n===Ie||n===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,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 vn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(gn,{idx:l,col:o,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(hs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Vo({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,l]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),x=f?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(f),transition:p}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":k?"string":w?"date":"string";if(r===Te){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,role:"groupby",label:Pe(S.column_name,"month"),granularity:"month"};c(t.id,D)}}if(r===Me){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,label:Pe(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,D)}}if(r===Ie){const D={id:t.id,name:S.column_name,type:L,role:"metric",label:He(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};i(t.id,D)}}function b(){if(r===Ie)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(vn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Ie)return e.jsx(Fo,{column:t});if((r===Te||r===Me)&&S)return e.jsx(zo,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Te||r===Me)&&v}),children:e.jsx(Po,{col:t,onChange:j,droppableId:r})})}function E(){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:()=>l(!o),children:o?e.jsx(wa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,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:[E(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ns({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:l}){var x,v;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),m=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),h=i||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,f=u?r:n,p=o===ts?"Rows":o===ns?"Pivot Columns":"Columns";function g(){if(!f||f.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:n==null?void 0:n.map(j=>j.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:a}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:p})]}),g(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(j=>j.id===sn.id?e.jsx(_o,{},j.id):e.jsx(Vo,{droppableId:t,type:o,column:j,onRemoveColumn:l},j.id))})]})})}function _o(){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 bn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function Uo(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Pn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function f(j,b){const C=p(j);return C?C.role==="metric"?b==="asc"?u:m:b==="asc"?i:d:null}function p(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};l(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>Ue(j.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:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(bn,{id:Ue(j.columnId),type:_s,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(Et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ws,{className:"w-[175px] text-sm",children:((b=p(j.columnId))==null?void 0:b.label)||((C=p(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:f(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.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"})})})]})},j.columnId)},Ue(j.columnId))})]})})}function $o(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),l=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(v){i(v)}function h(v){d(v)}function f(v){u(v)}let p="Group By",g="Metrics",x="Stack By";return a==="table"&&(p="Rows",g="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(un,{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(Ns,{onRemoveColumn:m,sortableType:ts,id:Te,label:p,columns:t,previewColumns:n}),e.jsx(Ns,{onRemoveColumn:f,sortableType:ns,id:Me,label:x,columns:l,previewColumns:c}),e.jsx(Ns,{onRemoveColumn:h,sortableType:ws,id:Ie,label:g,columns:r,previewColumns:o}),e.jsx(Uo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Js({children:t,column:a,id:n,sortableType:r,className:o}){const[l,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var f,p;return(p=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:p.some(g=>g.filterColumnName===a.name)});function m(h){i(h)}return e.jsx(bn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),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:a.name}),u&&e.jsx("button",{onClick:()=>d(a),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(a),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",!l&&"rounded-b-md",l&&"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",o),children:t})]})]})})}function qo({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,E;return(E=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:E.filters}),o=s.useEditorStore(C=>{var R,E;return(E=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:E.find(S=>S.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:f,isLoading:p,isFetching:g,isError:x}=s.useFilterQuery(h),v=A.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(E=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return E[S]===void 0&&(S=S.toLowerCase()),{id:E[S],value:E[S]}}):[]},[f,h.column]);function j(C){const R=C.map(E=>E.id);m(t.name,R)}function b(){return p||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.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(Yo,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Js,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function Yo({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Go({column:t,sortableType:a}){const[n,r]=A.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:p,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const E={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,E)}function b(){v(t.name,null,!0),g(x)}function C(){return d||u?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"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:p,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Js,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Ho({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,x;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},m=c||((x=(g=i==null?void 0:i.data)==null?void 0:g.current)==null?void 0:x.type)===o;function h(){if(!p||p.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 f(v){const j=s.isDateDataType(v.type);return v.id===sn.id?e.jsx(Js,{id:v.id,sortableType:o,column:v,children:e.jsx(Qo,{})},v.id):j?e.jsx(Go,{droppableId:t,sortableType:o,column:v},v.id):e.jsx(qo,{droppableId:t,sortableType:o,column:v},v.id)}const p=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.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:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:p==null?void 0:p.map(v=>f(v))})]})})}function Qo(){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 Ko(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Ho,{onRemoveColumn:r,sortableType:ks,id:Ds,label:"Filters",columns:t,previewColumns:a})})}function Wo(){const t=s.useEditorStore(l=>l.card),a=s.useEditorStore(l=>l.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage: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(us,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(ja,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(rn,{sql:r==null?void 0:r.sql,error: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($s,{}),e.jsx(Us,{variant:"default"})]})]})}function Jo(){const t=A.useRef(null),a=A.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=a.current)==null||m.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Kr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Ro,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ke,{})})]}):e.jsx(Ke,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx($o,{})})}),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(Wo,{}),e.jsx(Ko,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Ke,{})})]})})]}):e.jsx(Ke,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?l():c()})}function Xo(t){const a=s.useAIInteractionStore(F=>F.currentAIContext),[n,r]=A.useState(""),[o,l]=A.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(F=>{var J;return(J=F==null?void 0:F.card)==null?void 0:J.sql}),d=s.useEditorStore(F=>F.isDevMode),u=s.useEditorStore(F=>{var J;return(J=F==null?void 0:F.card)==null?void 0:J.python}),{setCardPython:m,setCardSql:h,setRunSql:f,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(F=>F.currentAssitantScope)||[],v=s.useEditorStore(F=>F.userInputForAI),j=s.useEditorStore(F=>F.triggerAIRun),b=s.useEditorStore(F=>F.card),C=s.useEditorStore(F=>F.selectedDatabaseName),R=s.useEditorStore(F=>F.selectedTableName),E=s.useEditorStore(F=>F.selectedConnectionId),S=s.useEditorStore(F=>F.selectedSchemaName),N=s.useDashboardStore(F=>F.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:D,setCurrentAssitantScope:O,setCardConfig:M}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:T}=s.useEditorAside(),{messages:B,setMessages:z,reload:V,error:P,append:X,input:K,setInput:_,status:$,handleInputChange:q,handleSubmit:U,stop:G}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:F=>{console.log("on error",F)},onToolCall:Q,onFinish(F,J){Y(J.usage),r(""),J.finishReason==="stop"&&r("")}});A.useEffect(()=>{j&&v&&(X({role:"user",content:v}),D(!1))},[j,v,X,D]);async function Q({toolCall:F}){var J,ie,be,ke;if(["createChartFromSql","createForecast"].includes(F.toolName)){const ne=F.args.sql,le=F.args.python,ce=F.args.chartType;return p(ce),h(ne),m(le),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(F.toolName==="getTableColumns")r("Getting table columns...");else{if(F.toolName==="getUserSql")return i?{status:"success",sql:i,python:u||""}:{status:"error",message:"No SQL found"};if(F.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(F.toolName==="generateQueryConfig"){r("Generating query config...");const ne=F.args.chartType,le=F.args.queryConfig;F.args.cardConfig,p(ne),M(le),h(void 0),m(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(be=ce==null?void 0:ce.data)!=null&&be.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(ke=ce==null?void 0:ce.data)==null?void 0:ke.records}}else r("Analyzing...")}}function Y(F){l(J=>J?{promptTokens:J.promptTokens+F.promptTokens,completionTokens:J.completionTokens+F.completionTokens,totalTokens:J.totalTokens+F.totalTokens}:F)}function Z(F){const J=s.removeFromScopeArray(x,F);te(J)}function te(F){const J=s.sanitizeAIScope(F);O(J),z(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const F={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:T||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||""},J=s.dedup([...x,F]);te(J)}function se(){const F={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||"",datamodelId:T||""};if(!s.isInAiScopeArray([...N||[],...x],F)||x.length===0){const ie=s.dedup([...N||[],...x,F]).filter(be=>be.connectionId===F.connectionId);te(ie)}}const oe=!["ready","error"].includes($),H=s.getErrorMessage(P);return{messages:B,setMessages:z,reload:V,append:X,input:K,setInput:_,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:G,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:H}}const Zo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function jt(){const t=A.useRef(null),a=A.useRef(null),[n,r]=A.useState(!1),[o,l]=A.useState(s.isDevEnv),[c,i]=A.useState(!1),[d,u]=A.useState(!1),m=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),f=s.useDashboardStore(G=>G.dashboard.aiContext),p=s.useEditorStore(G=>G.card.dataSource),g=s.useEditorStore(G=>G.actions.setCardSql),x=s.useEditorStore(G=>G.actions.setRunSql),v=s.useEditorStore(G=>G.showAIDialog),j=s.useDashboardStore(G=>G.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:k,append:w,input:L,setInput:D,isLoading:O,handleInputChange:M,handleSubmit:I,stop:y,chatStatus:T,llmUsage:B,errorMessage:z}=Xo();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),A.useEffect(()=>{var G;v&&((G=a.current)==null||G.focus(),h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[v,p,h]);function V(G,Q){Q==="sql"?(g(G),x(!0)):Q==="python"&&(C(G),x(!0))}function P(){var G;(G=f==null?void 0:f.selectedEntities)==null||G[0],u(!0)}function X(){m.selectedEntities.length===0&&h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function K(G){X();const Q={role:"user",content:G.title+" "+G.subtitle};w(Q)}function _(G){X(),w({role:"user",content:G})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.filter(G=>G.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:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:T,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!E&&e.jsx(s.Placeholders,{onClick:K,placeholders:Zo}),e.jsx("div",{children:U&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:_})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:D,stop:y,input:L,handleInputChange:M,handleSubmit:G=>{X(),I(G)},isLoading:O,onFocus:()=>{}}),B&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.promptTokens," prompt tokens,"," ",B.completionTokens," completion tokens,"," ",B.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:d,onOpenChange:u,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Nn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const l=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return l===t&&c===a||l===a&&c===t})}function ei(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Nn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function Es(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Ts(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Xs=t=>{var D;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,f=A.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),p=A.useCallback((O,M)=>{if(h)switch(O){case"groupBy":{a(h,{groupByColumns:M});break}case"metrics":{a(h,{metricColumns:M});break}case"pivotBy":{a(h,{pivotByColumns:M});break}case"sortBy":{a(h,{sortByColumns:M});break}}},[h,a]),g=A.useCallback((O,M,I)=>{if(!h)return;const T=f(O)[M];if(T)switch(O){case"groupBy":n(h,T.id,{label:I});break;case"metrics":r(h,T.id,{label:I});break;case"pivotBy":o(h,T.id,{label:I});break;case"sortBy":l(h,T.id,{label:I});break}},[h,f,n,r,o,l]),x=A.useCallback((O,M)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aggregate:M,label:s.getAggregationLabel(y.name,M)})},[h,f,r]),v=A.useCallback((O,M,I)=>{if(!h)return;const T=f("groupBy")[O];if(!T)return;const B={dateFormat:M};M==="custom"&&I?B.customFormat=I:B.customFormat=void 0,n(h,T.id,B)},[h,f,n]),j=A.useCallback((O,M)=>{if(!h)return;const y=f("groupBy")[O];y&&n(h,y.id,{granularity:M})},[h,f,n]),b=A.useCallback((O,M)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aliasTemplate:M})},[h,f,r]),C=A.useCallback((O,M)=>{if(console.log("handleValueAliasesChange",O,M),!h)return;console.log("handleValueAliasesChange",O,M);const y=f("metrics")[O];y&&(console.log("handleValueAliasesChange",M),r(h,y.id,{valueAliases:M}))},[h,f,r]),R=A.useCallback(O=>{h&&a(h,{comparisonType:O})},[h,a]),E=A.useCallback(O=>{h&&a(h,{showTrendline:O})},[h,a]),S=A.useCallback(O=>{h&&a(h,{trendlineWindow:O})},[h,a]),N=A.useCallback(O=>{h&&a(h,{trendlineGranularity:O})},[h,a]),k=A.useCallback(O=>{h&&a(h,{targetValue:O})},[h,a]),w=A.useCallback(O=>{var V;if(!h)return;const M=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,y=ei(O,M,I);if(!y.isValid){y.showError&&Es();return}const T=s.getSmartContainerForField(O),B=f(T);if(Ts(O,B))return;const z=s.getNewField(O,T);z&&p(T,[...B,z])},[h,(D=t==null?void 0:t.config)==null?void 0:D.joinPlan,f,p]),L=A.useCallback((O,M)=>{if(!h)return;const y=f(O)[M];if(y){if(O!=="sortBy"){const T=f("sortBy"),B=T.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));B.length!==T.length&&a(h,{sortByColumns:B})}switch(O){case"groupBy":c(h,y.id);break;case"metrics":i(h,y.id);break;case"pivotBy":d(h,y.id);break;case"sortBy":u(h,y.id);break}}},[h,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:p,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:k,cardType:m}};function si({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 ti({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(g=>g.card),{handleFieldClick:m}=Xs(u),h={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const f=g=>{const x=(g||"").toLowerCase();switch(s.getDataType(x)){case"number":return $e;case"date":return s.Calendar;case"boolean":return es;case"json":return ot;case"geo":return it;default:return Ge}},p=g=>{const x=(g||"").toLowerCase(),v=s.getDataType(x);return v==="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(Ge,{className:"h-3 w-3"})}):v==="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($e,{className:"h-3 w-3"})}):v==="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"})}):v==="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(es,{className:"h-3 w-3"})}):v==="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(ot,{className:"h-3 w-3"})}):v==="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(it,{className:"h-3 w-3"})}):v==="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(wt,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,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:[p(t.dataType),e.jsx(s.TooltipProvider$1,{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(si,{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(Ea,{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 ni(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(C=>m(C)===n)).reduce((C,R)=>{const E=R.qualifiedEntityName||"Other Fields";return C[E]||(C[E]={label:s.toLabel(R.entityName),fields:[]}),C[E].fields.push(R),C},{}),g=Object.keys(f),x=u.filter(C=>m(C)==="dimensions").length,v=u.filter(C=>m(C)==="metrics").length,j=u.filter(C=>m(C)==="calculated").length,b=u.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?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:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.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:[l.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:C=>a(C.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),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:u.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:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(wt,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(f).map(([C,R])=>{const E=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,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",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:E.label||E.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(S=>e.jsx(ti,{field:S},S.id))})})]},C)})}),Object.keys(f).length===0&&l.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(f).length===0&&l.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 ai(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ni,{})," "]})}function ri({initialJoinPlan:t,availableDataSources:a}){const[n,r]=A.useState(t),[o,l]=A.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,N={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({...n,joins:[...n.joins,N]}),l(new Set([...o,N.id]))},i=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),l(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var D,O;const k=n.joins.find(M=>M.id===S);if(!k)return;const w={...k,...N},L=n.joins.map(M=>M.id===S?w:M);if((D=w.source)!=null&&D.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const M=a.find(B=>{var z;return B.name===((z=w.source)==null?void 0:z.name)}),I=a.find(B=>{var z;return B.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},T=[...w.joinKeyGroups];T[0]={...T[0],keys:[y]},w.joinKeyGroups=T,L[L.findIndex(B=>B.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N>0){const k=[...n.joins],w={...k[N]},L={...k[N-1]};k[N]=L,k[N-1]=w,k.forEach((O,M)=>{O.sequence=M+1});const D={...n,joins:k};r(D)}},moveJoinDown:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N<n.joins.length-1){const k=[...n.joins],w={...k[N]},L={...k[N+1]};k[N]=L,k[N+1]=w,k.forEach((O,M)=>{O.sequence=M+1});const D={...n,joins:k};r(D)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),l(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const k=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:k},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const k=n.joins.find(L=>L.id===S);if(!k)return;const w=[...k.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const k=n.joins.find(M=>M.id===S);if(!k)return;const w=a.find(M=>M.name===k.source.name),L=a.find(M=>M.name===k.target.name),D=[...k.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",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:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};D[N]={...D[N],keys:[...D[N].keys,O]},d(S,{joinKeyGroups:D})},updateJoinKey:(S,N,k,w,L)=>{const D=n.joins.find(T=>T.id===S);if(!D)return;const O=a.find(T=>T.name===D.source.name),M=a.find(T=>T.name===D.target.name),I=[...D.joinKeyGroups],y=I[N].keys[k];w==="sourceColumnName"&&O?I[N].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&M?I[N].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[k]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(k,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
420
+ FROM ${N.name}`;return S.forEach(w=>{const L=a.find(M=>M.name===w.target.name);if(!L)return;const D=w.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const I=M.keys.filter(y=>{var T,B,z,V;return((T=y.source)==null?void 0:T.name)&&((B=y.target)==null?void 0:B.name)&&((z=y.source)==null?void 0:z.entityName)&&((V=y.target)==null?void 0:V.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${M.operator} `)})`:I[0]}).filter(Boolean),O=D.length>1?D.join(" OR "):D[0]||"condition_here";k+=`
421
421
  ${w.joinType} JOIN ${L.name}
422
- ON ${O}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(k=>!k.source.name||!k.target.name||!k.operator))))}}function ri({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:p,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:E,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:D,isValidConfiguration:w}=ai({initialJoinPlan:t,availableDataSources:a}),L=k=>{const O=c.find(A=>A.entityName===k);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:k=>{const O=a.find(A=>A.name===k);u({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:k,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.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:D()})]}),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 O=a.find(y=>y.name===k.source.name),A=a.find(y=>y.name===k.target.name),I=d.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,O&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(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:()=>g(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:I?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"})})]})]})}),I&&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:y=>{const T=a.find(F=>F.name===y);f(k.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(k.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:y=>f(k.id,{joinType:y}),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:y=>{const T=a.find(F=>F.name===y);f(k.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.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?j(k.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),k.source.name&&k.target.name&&O&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(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((y,T)=>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 ",T+1]}),T>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:y.operator,onValueChange:F=>C(k.id,T,F),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:()=>R(k.id,T),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.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:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>S(k.id,T,z,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(k.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>S(k.id,T,z,"operator",_),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:F.target.name,onValueChange:_=>S(k.id,T,z,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(k.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(k.id,T,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(k.id,T),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.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(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function jt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(ri,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function oi({joins:t,baseEntityId:a,availableDataSources:n,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 o=[...t].sort((c,i)=>c.sequence-i.sequence),l=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=n.find(d=>d.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((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=n.find(d=>d.name===o.source.name),i=n.find(d=>d.name===o.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:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.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:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.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 ii(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((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,o]=M.useState(!1),l=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),o(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const f=[...n.joins].sort((x,v)=>x.sequence-v.sequence),p=n.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
423
- FROM ${p.name}`;return f.forEach(x=>{const v=l.find(C=>C.name===x.target.name);if(!v)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(E=>{var S,N,D,w;return((S=E.source)==null?void 0:S.name)&&((N=E.target)==null?void 0:N.name)&&((D=E.source)==null?void 0:D.entityName)&&((w=E.target)==null?void 0:w.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
422
+ ON ${O}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function oi({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:p,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:E,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:k,isValidConfiguration:w}=ri({initialJoinPlan:t,availableDataSources:a}),L=D=>{const O=c.find(M=>M.entityName===D);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:D=>{const O=a.find(M=>M.name===D);u({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:D,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(D=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:k()})]}),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(D=>{const O=a.find(y=>y.name===D.source.name),M=a.find(y=>y.name===D.target.name),I=d.has(D.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:D.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",D.sequence,O&&M&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",M.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(D.id),disabled:D.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(D.id),children:I?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(D.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:D.source.name,onValueChange:y=>{const T=a.find(B=>B.name===y);f(D.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(D.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:y=>f(D.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:D.target.name,onValueChange:y=>{const T=a.find(B=>B.name===y);f(D.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},disabled:!D.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:D.source.name?j(D.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),D.source.name&&D.target.name&&O&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((y,T)=>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 ",T+1]}),T>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:y.operator,onValueChange:B=>C(D.id,T,B),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:()=>R(D.id,T),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.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:y.keys.map((B,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.source.name,onValueChange:V=>S(D.id,T,z,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(D.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:B.operator,onValueChange:V=>S(D.id,T,z,"operator",V),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:B.target.name,onValueChange:V=>S(D.id,T,z,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(D.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,T,z),children:e.jsx(s.X,{className:"size-3.5"})})]},B.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(D.id,T),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function yt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(oi,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function ii({joins:t,baseEntityId:a,availableDataSources:n,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 o=[...t].sort((c,i)=>c.sequence-i.sequence),l=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=n.find(d=>d.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((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=n.find(d=>d.name===o.source.name),i=n.find(d=>d.name===o.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:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.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:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.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 li(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((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,o]=A.useState(!1),l=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),o(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const f=[...n.joins].sort((x,v)=>x.sequence-v.sequence),p=n.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
423
+ FROM ${p.name}`;return f.forEach(x=>{const v=l.find(C=>C.name===x.target.name);if(!v)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(E=>{var S,N,k,w;return((S=E.source)==null?void 0:S.name)&&((N=E.target)==null?void 0:N.name)&&((k=E.source)==null?void 0:k.entityName)&&((w=E.target)==null?void 0:w.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
424
424
  ${x.joinType} JOIN ${v.name}
425
- ON ${b}`}),g};return l.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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(oi,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function li({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.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:a||s.getDisplayName(t)}),l&&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:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>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})]},d))})]})})}function ci({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((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=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(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.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-${a.type}-${a.name}-${n}`)})})]})})}function di({isVisible:t,onToggleVisibility:a}){s.useEditorStore(m=>m.isDevMode),s.useEditorStore(m=>m.card.connectionId),s.useDashboardStore(m=>m.isVisualEditing);const[n,r]=M.useState(!1),[o,l]=M.useState(!0),c=s.useEditorStore(m=>m.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.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":!o}),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:()=>l(!o),className:"h-6 w-6 p-0",children:o?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:a,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 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((m,h)=>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(m),e.jsx("button",{onClick:f=>{f.stopPropagation();const p=u.selectedEntities.filter(g=>!(g.name===m.name&&g.type===m.type));i({...d,...c,selectedEntities:p})},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(li,{entity:m})]},`${m.type}-${m.name}-${h}`)),u.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:["+",u.selectedEntities.length-3," more"]})}),e.jsx(ci,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(ii,{})]})]}),e.jsx(ni,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Xe=[{id:"table",icon:ls,label:"Table"},{id:"bar",icon:rs,label:"Bar Chart"},{id:"line",icon:os,label:"Line Chart"},{id:"area",icon:wt,label:"Area Chart"},{id:"stackedBar",icon:Ts,label:"Stacked Bar Chart"},{id:"combo",icon:Qn,label:"Combo Chart"},{id:"stackedLine",icon:Ks,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:is,label:"Pie Chart"},{id:"doughnut",icon:Ms,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Rs,label:"Radar Chart"},{id:"polarArea",icon:qs,label:"Polar Area Chart"},{id:"tornado",icon:Os,label:"Tornado Chart"},{id:"range",icon:Is,label:"Range Chart"},{id:"kpi",icon:Qs,label:"KPI"},{id:"text",icon:Ct,label:"Text"},{id:"map",icon:Ls,label:"Map"}],Xs=t=>{const a=t.toLowerCase();for(const n of Xe)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},ui="chart-selector-standard-first";function mi(){const[t,a]=s.useLocalStorageState(ui,!0);return{standardFirst:t,updatePreference:a}}const yt=({pluginVisual:t,index:a,onSelect:n})=>{const r=us(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Xs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,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"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),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}-${a}`)},vt=["default","standardPlugin","customPlugin"];function hi({selectedChart:t,onChartChange:a}){var S;const[n,r]=M.useState([]),[o,l]=M.useState(!1),{data:c}=$s();mi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";Fs(d);const{setCardType:u,setCardPreferences:m,setIsDevMode:h}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:p,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>x?[x,...vt.filter(N=>N!==x)]:vt,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(k){return console.error(`Failed to load manifest for plugin ${L.label}`,k),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),m({}),u(N),["custom","text","map"].includes(N)&&(h(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),m({}),u("custom"),p({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var D;if(t==="custom"){const w=s.useEditorStore.getState().card;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=Xe.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var D,w;if(t==="custom"){const L=s.useEditorStore.getState().card,k=(D=L==null?void 0:L.customCardPreferences)==null?void 0:D.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(k&&O)return e.jsx(xi,{icon:k,componentName:O});if(O){const A=Xs(O);if(A)return A}return e.jsx($e,{className:"h-4 w-4"})}const N=Xe.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx($e,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] 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."}),j.map(N=>{if(N==="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:x==="default",onCheckedChange:D=>v(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Xe.map(D=>{const w=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>b(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=n.filter(w=>w.pluginType==="standard");return D.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:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=n.filter(w=>w.pluginType==="custom");return D.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:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const xi=({icon:t,componentName:a})=>{const n=us(),r=Xs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx($e,{className:"h-4 w-4"})},Nn=({dataType:t})=>{const a=s.getDataType(t);return a==="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(Ge,{className:"h-3 w-3"})}):a==="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(Ue,{className:"h-3 w-3"})}):a==="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"})}):a==="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(Ze,{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(Ge,{className:"h-3 w-3"})})};function pi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[o,l]=M.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[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:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==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:()=>{a(n),l(!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),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function fi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[o,l]=M.useState(""),[c,i]=M.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[o]=c,a(f),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,f],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.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),l(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function bt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&l!==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:u,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"})})]})]})}function gi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var et;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),p=s.useEditorStore(X=>X.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:w}=Ys(p),[L,k]=M.useState(!1),[O,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[T,F]=M.useState(!!t.customFormat),[z,_]=M.useState(t.granularity||"day"),[P,Y]=M.useState(t.aliasTemplate||""),[W,V]=M.useState(t.valueAliases||{}),$=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&v(n,X,""))},q=X=>{y(X),a==="groupBy"&&v(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&j(n,X)},H=X=>{Y(X),a==="metrics"&&b(n,X)},Q=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{g(a,n,X)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(m),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",K=[{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..."}],B=!oe&&a!=="pivotBy",J=se&&a==="groupBy",ie=!oe&&se&&a==="groupBy",ye=oe&&se&&a==="groupBy",ke=oe&&a==="metrics"&&((et=p.config)==null?void 0:et.comparisonType)==="target",ne=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce=()=>B?e.jsx(bt,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,wn=()=>J?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:U,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"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,kn=()=>ie?e.jsx(e.Fragment,{children: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:T?"custom":O,onValueChange:$,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:K.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),T&&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:I,onChange:X=>{X.stopPropagation(),q(X.target.value)},onClick:X=>X.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,Dn=()=>{var X,ve,Re,st,tt;return ye?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:((X=p.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,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:((ve=p.config)==null?void 0:ve.showTrendline)||!1,onCheckedChange:S})]})}),((Re=p.config)==null?void 0:Re.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:((st=p.config)==null?void 0:st.trendlineWindow)||30,onChange:In=>{const An=parseInt(In.target.value)||30;N(An)},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:((tt=p.config)==null?void 0:tt.trendlineGranularity)||"day",onValueChange:D,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},En=()=>{var X,ve;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(bt,{value:((X=p.config)==null?void 0:X.targetValue)!==void 0&&((ve=p.config)==null?void 0:ve.targetValue)!==null?String(p.config.targetValue):"",onSave:Re=>{!isNaN(Number(Re))&&Re!==null?w(Number(Re)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},Tn=()=>ne?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:X=>{x(n,X)},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,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(yn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(pi,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(fi,{valueAliases:W,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Nn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),k(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ve=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ve),o(ve)},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:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),ce(),wn(),kn(),Dn(),En(),Tn()]})]})}function ji({concept:t}){const a=()=>{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$1,{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:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.card.type),h=a.length>0,f=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const p=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4",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:n}),p&&e.jsx(ji,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 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":"border-muted-foreground/20 bg-background"}`,children:a.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:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(gi,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:m})})},g.id)})})})})]})}function yi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},m=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:m().label,placeholder:m().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function vi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 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(hi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(ds,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(wa,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(yi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function bi({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=(E,S)=>{const N=D=>D.id===E?{...D,conditions:D.conditions.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},f=(E,S)=>{const N=D=>D.id===E?{...D,groups:D.groups.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},p=(E,S,N,D)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(k=>k.id===S?{...k,[N]:D}:k)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(D)};r(D(n))},x=(E,S)=>{const N=D=>D.id===E?{...D,logicalOperator:S}:{...D,groups:D.groups.map(N)};r(N(n))},v=(E,S)=>{const N=D=>D.id===E?{...D,negate:S}:{...D,groups:D.groups.map(N)};r(N(n))},j=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},b=(E,S,N)=>{const D=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=D=>{let w="";typeof D.field=="object"?w=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:w=String(D.field);const L=D.operator;let k=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof k=="string"?k=`'${k}'`:Array.isArray(k)&&(k=`'${k.join(", ")}'`);else if(D.field.dataType==="date")(typeof k=="string"||k instanceof Date)&&(k=`DATE('${k}')`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(k)?O=k.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof k=="string"?O=k.split(",").map(A=>{const I=A.trim();return D.field.dataType==="string"?`'${I}'`:I}):typeof k=="number"&&(O=[String(k)]),k=`(${O.join(", ")})`}switch(L){case"contains":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;case"startsWith":return typeof k=="string"?`${w} LIKE '${k.replace(/'/g,"")}%'`:`${w} LIKE '${String(k)}%'`;case"endsWith":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;default:return`${w} ${L} ${k}`}},N=D=>{const w=D.conditions.map(S),L=D.groups.map(I=>N(I)),k=[...w,...L].filter(Boolean);if(k.length===0)return"";const O=k.join(` ${D.logicalOperator} `),A=k.length>1?`(${O})`:O;return D.negate?`NOT ${A}`:A};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:p,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ni({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Ci=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(na,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Si=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function wi({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return n.forEach(u=>{const m=Si(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ni,{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(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).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:[Ci(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,p)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),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)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+p))]},`${d}-${m}`))},d))})]})})]})}function Zs(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=Zs(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.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:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(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:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}const Cn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Cn(n)}),a};function Di({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=Zs(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:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ei=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ti=["=","!=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Mi=["=","!=",">",">=","<","<=","in","not in"];function Li(t){switch(t){case"string":return Ti;case"number":return Ii;case"boolean":return Ai;case"date":return Mi;default:return Ei}}function Sn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=Zs(t.field),j={transform:s.CSS.Transform.toString(f),transition:p};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(wi,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Li(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),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..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Di,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.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:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Ri({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:p,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id){const O=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&u(t.id,O,A)}},D=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&m(n,O,A)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,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:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),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:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Sn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+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:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Oi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=bi({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=M.useState(!1),D=(k,O,A)=>{const I=y=>y.id===k?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:A,dataType:A.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(k,O=0,A)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.conditions.findIndex(_=>_.id===y.id),z=k.conditions.findIndex(_=>_.id===T.id);F!==-1&&z!==-1&&v(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.conditions.map((I,y)=>e.jsx(Sn,{condition:I,index:y,groupId:k.id,groupLogicalOperator:k.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:p},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.groups.findIndex(_=>_.id===y.id),z=k.groups.findIndex(_=>_.id===T.id);F!==-1&&z!==-1&&j(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.groups.map(I=>w(I,O+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:()=>d(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:()=>u(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},k.id):e.jsx(Ri,{group:k,depth:O,parentGroupId:A,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:p},k.id),L=Cn(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..."})]}):w(l),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=>N(!!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)"})]})}),C&&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:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&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:u=>{u.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(Oi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Fi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var p;const[o,l]=M.useState(null),c=s.useEditorStore(g=>g.card),i=(p=c==null?void 0:c.config)==null?void 0:p.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=M.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),m=M.useCallback(g=>{l(g.active.id)},[]),h=M.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){l(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!bn(w,E.qualifiedEntityName,i)){Ds(),l(null);return}}else{Ds(),l(null);return}}const N=n(R);if(Es(E,N)){l(null);return}const D=s.getNewField(E,R);l(null),r(R,[...N,D]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const D=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Es(N,S)||r(R,[...S,D]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,D]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(D=>D.id===j),N=E.findIndex(D=>D.id===b);if(S!==N){const D=s.arrayMove(E,S,N);r(C,D)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:m,handleDragEnd:h}}function zi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(p=>p.isDevMode),o=s.useEditorStore(p=>p.card);s.isExplorerCard(o);const{config:l}=M.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(p=>p.showAIDialog),u=s.useEditorStore(p=>p.frame),m=s.useManagementStore(p=>p.selectedVisual),h=(m==null?void 0:m.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),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(Us,{}),n&&!h&&e.jsx(Vs,{variant:"default"}),h&&e.jsx(Kr,{}),a&&s.isDevEnv]})]})}function Pi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 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"}),n.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":"Query"})]})})}const _i=[{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 Vi(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[o,l]=M.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.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:_i.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Ui({isOpen:t,onClose:a}){const n=qt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=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(o),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,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:a,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:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function $i({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var O;const p=s.useEditorStore(A=>A.card),g=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(A=>A.showAIDialog),[j,b]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:D}=s.useDashboardCardQuery(u);function w(){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(p.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(g||{},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(u.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...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const L=A=>{if(!p.config)return;if(!A.length){x(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,y=A.map(({id:T,desc:F})=>{var Y,W;const z=(Y=I.metricColumns)==null?void 0:Y.find(V=>V.label===T),_=(W=I.groupByColumns)==null?void 0:W.find(V=>V.label===T),P=z||_;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(T=>T!==null);x(p.id,{...I,sortByColumns:y})},k=M.useMemo(()=>{var A,I;return(I=(A=p.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=p.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(zi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),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"&&v&&e.jsx(un,{variant:"outline"}),e.jsx(Pi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Vi,{})}),v&&e.jsx(ds,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(mn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!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(Na,{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:N||D?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(hn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||D)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:k})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(nn,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx(Ui,{isOpen:j,onClose:()=>b(!1)})]})]})}function qi({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!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 ${a?"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(Nn,{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 Gi=()=>{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 a=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},n=r=>{var o;if((o=r.reason)!=null&&o.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",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var V,$;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[o,l]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);M.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},p=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},v=q=>{m(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:D=[],isLoading:w,error:L}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:A,setFieldsForContainer:I}=Ys(O),{activeField:y,handleDragStart:T,handleDragEnd:F}=Fi({activeCardId:j.activeCardId,sourceFields:D,getFieldsForContainer:A,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},_=q=>{var U;E(q,{config:{...(U=j.cards.find(H=>H.id===q))==null?void 0:U.config,filters:void 0}})},P=D,Y=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(H=>{U+=Y(H)}),U},W=Y(((V=O==null?void 0:O.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(di,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(vi,{selectedChart:h,onChartChange:v,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($i,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:p,onAdvancedToggle:g,onFiltersClick:x,filterCount:W,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&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"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:_,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(qi,{activeField:y||null})})]})}function Ki({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:p,sensors:g}=Rr();M.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function x(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(sn,{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(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(gt,{})})]})]})}function j(){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(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(gt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Qi(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ki,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),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(Ps,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(sn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Yi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.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)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.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 Xi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Yi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function Zi(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),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:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}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 el({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(Zi,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Tr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Qi,{}),e.jsx(Xi,{})]})]})]})]})})}exports.DashboardPlus=el;exports.ResourceManagementPanel=Zt;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Lt;exports.downloadPdf=Ot;exports.getDashbaordStateWithoutData=Bs;
425
+ ON ${b}`}),g};return l.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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(ii,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ci({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.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:a||s.getDisplayName(t)}),l&&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:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>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})]},d))})]})})}function di({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((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=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(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.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-${a.type}-${a.name}-${n}`)})})]})})}function ui({isVisible:t,onToggleVisibility:a}){s.useEditorStore(m=>m.isDevMode),s.useEditorStore(m=>m.card.connectionId),s.useDashboardStore(m=>m.isVisualEditing);const[n,r]=A.useState(!1),[o,l]=A.useState(!0),c=s.useEditorStore(m=>m.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.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":!o}),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:()=>l(!o),className:"h-6 w-6 p-0",children:o?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:a,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 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((m,h)=>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(m),e.jsx("button",{onClick:f=>{f.stopPropagation();const p=u.selectedEntities.filter(g=>!(g.name===m.name&&g.type===m.type));i({...d,...c,selectedEntities:p})},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(ci,{entity:m})]},`${m.type}-${m.name}-${h}`)),u.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:["+",u.selectedEntities.length-3," more"]})}),e.jsx(di,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(li,{})]})]}),e.jsx(ai,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Ze=[{id:"table",icon:cs,label:"Table"},{id:"bar",icon:os,label:"Bar Chart"},{id:"line",icon:is,label:"Line Chart"},{id:"area",icon:Dt,label:"Area Chart"},{id:"stackedBar",icon:Is,label:"Stacked Bar Chart"},{id:"combo",icon:Kn,label:"Combo Chart"},{id:"stackedLine",icon:Qs,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:ls,label:"Pie Chart"},{id:"doughnut",icon:Ls,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Os,label:"Radar Chart"},{id:"polarArea",icon:Ys,label:"Polar Area Chart"},{id:"tornado",icon:Fs,label:"Tornado Chart"},{id:"range",icon:Ms,label:"Range Chart"},{id:"kpi",icon:Ks,label:"KPI"},{id:"text",icon:St,label:"Text"},{id:"map",icon:Rs,label:"Map"}],Zs=t=>{const a=t.toLowerCase();for(const n of Ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}return null},mi="chart-selector-standard-first";function hi(){const[t,a]=s.useLocalStorageState(mi,!0);return{standardFirst:t,updatePreference:a}}const vt=({pluginVisual:t,index:a,onSelect:n})=>{const r=ms(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Zs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,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"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),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}-${a}`)},bt=["default","standardPlugin","customPlugin"];function xi({selectedChart:t,onChartChange:a}){var S;const[n,r]=A.useState([]),[o,l]=A.useState(!1),{data:c}=qs();hi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";zs(d);const{setCardType:u,setCardPreferences:m,setIsDevMode:h}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:p,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=A.useMemo(()=>x?[x,...bt.filter(N=>N!==x)]:bt,[x]);A.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(D){return console.error(`Failed to load manifest for plugin ${L.label}`,D),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),m({}),u(N),["custom","text","map"].includes(N)&&(h(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),m({}),u("custom"),p({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const N=Ze.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,D=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(D&&O)return e.jsx(pi,{icon:D,componentName:O});if(O){const M=Zs(O);if(M)return M}return e.jsx(qe,{className:"h-4 w-4"})}const N=Ze.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{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:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] 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."}),j.map(N=>{if(N==="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:x==="default",onCheckedChange:k=>v(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>b(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(N==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.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:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.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:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const pi=({icon:t,componentName:a})=>{const n=ms(),r=Zs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},Cn=({dataType:t})=>{const a=s.getDataType(t);return a==="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(Ge,{className:"h-3 w-3"})}):a==="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($e,{className:"h-3 w-3"})}):a==="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"})}):a==="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(es,{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(Ge,{className:"h-3 w-3"})})};function fi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[o,l]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[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:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==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:()=>{a(n),l(!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),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function gi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[o,l]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[o]=c,a(f),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,f],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.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),l(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Nt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&l!==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:u,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"})})]})]})}function ji({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var tt;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),p=s.useEditorStore(W=>W.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=Xs(p),[L,D]=A.useState(!1),[O,M]=A.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=A.useState(t.customFormat||""),[T,B]=A.useState(!!t.customFormat),[z,V]=A.useState(t.granularity||"day"),[P,X]=A.useState(t.aliasTemplate||""),[K,_]=A.useState(t.valueAliases||{}),$=W=>{W==="custom"?B(!0):(B(!1),M(W),a==="groupBy"&&v(n,W,""))},q=W=>{y(W),a==="groupBy"&&v(n,"custom",W)},U=W=>{var _e;V(W);const xe=(_e=H(W)[0])==null?void 0:_e.value;xe&&!T&&(M(xe),a==="groupBy"&&v(n,xe,"")),a==="groupBy"&&j(n,W)},G=W=>{X(W),a==="metrics"&&b(n,W)},Q=W=>{_(W),a==="metrics"&&C(n,W)},Y=W=>{g(a,n,W)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(m),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",H=W=>{switch(W){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..."}]}},F=H(z),J=!oe&&a!=="pivotBy",ie=se&&a==="groupBy",be=!oe&&se&&a==="groupBy",ke=oe&&se&&a==="groupBy",ne=oe&&a==="metrics"&&((tt=p.config)==null?void 0:tt.comparisonType)==="target",le=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:W=>{W.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Dn=()=>J?e.jsx(Nt,{value:t.label??"",onSave:Y,placeholder:"Display label...",type:"text"}):null,st=()=>ie?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:U,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(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,kn=()=>be?e.jsxs(e.Fragment,{children:[st(),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:T?"custom":O,onValueChange:$,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:F.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),T&&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:I,onChange:W=>{W.stopPropagation(),q(W.target.value)},onClick:W=>W.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,En=()=>{var W,ge,xe,_e,nt;return ke?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:((W=p.config)==null?void 0:W.comparisonType)||"none",onValueChange:E,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:((ge=p.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:S})]})}),((xe=p.config)==null?void 0:xe.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:((_e=p.config)==null?void 0:_e.trendlineWindow)||30,onChange:Mn=>{const An=parseInt(Mn.target.value)||30;N(An)},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:((nt=p.config)==null?void 0:nt.trendlineGranularity)||"day",onValueChange:k,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},Tn=()=>{var W,ge;return ne?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(Nt,{value:((W=p.config)==null?void 0:W.targetValue)!==void 0&&((ge=p.config)==null?void 0:ge.targetValue)!==null?String(p.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?w(Number(xe)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},In=()=>le?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:W=>{x(n,W)},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.jsx(vn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(fi,{aliasTemplate:P,onAliasTemplateChange:G}),e.jsx(gi,{valueAliases:K,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Cn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),D(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),o(ge)},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:W=>{W.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[ce(),Dn(),c==="kpi"&&st(),kn(),En(),Tn(),In()]})]})}function yi({concept:t}){const a=()=>{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$1,{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:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.card.type),h=a.length>0,f=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const p=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4",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:n}),p&&e.jsx(yi,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 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":"border-muted-foreground/20 bg-background"}`,children:a.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:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(ji,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:m})})},g.id)})})})})]})}function vi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},m=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:m().label,placeholder:m().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function bi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 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(xi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(us,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Da,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(vi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ni({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=(E,S)=>{const N=k=>k.id===E?{...k,conditions:k.conditions.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},f=(E,S)=>{const N=k=>k.id===E?{...k,groups:k.groups.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},p=(E,S,N,k)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(D=>D.id===S?{...D,[N]:k}:D)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(E,S)=>{const N=k=>k.id===E?{...k,logicalOperator:S}:{...k,groups:k.groups.map(N)};r(N(n))},v=(E,S)=>{const N=k=>k.id===E?{...k,negate:S}:{...k,groups:k.groups.map(N)};r(N(n))},j=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},b=(E,S,N)=>{const k=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let D=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(k.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(k.operator)){let O=[];Array.isArray(D)?O=D.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof D=="string"?O=D.split(",").map(M=>{const I=M.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(O=[String(D)]),D=`(${O.join(", ")})`}switch(L){case"contains":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${w} LIKE '${D.replace(/'/g,"")}%'`:`${w} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;default:return`${w} ${L} ${D}`}},N=k=>{const w=k.conditions.map(S),L=k.groups.map(I=>N(I)),D=[...w,...L].filter(Boolean);if(D.length===0)return"";const O=D.join(` ${k.logicalOperator} `),M=D.length>1?`(${O})`:O;return k.negate?`NOT ${M}`:M};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:p,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ci({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Si=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(aa,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wi=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Di({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=wi(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ci,{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(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).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:[Si(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,p)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),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)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+p))]},`${d}-${m}`))},d))})]})})]})}function et(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=et(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.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:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(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:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}const Sn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Sn(n)}),a};function Ei({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=et(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:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ti=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=","contains","startsWith","endsWith","in","not in"],Mi=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Li=["=","!=",">",">=","<","<=","in","not in"];function Ri(t){switch(t){case"string":return Ii;case"number":return Mi;case"boolean":return Ai;case"date":return Li;default:return Ti}}function wn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=et(t.field),j={transform:s.CSS.Transform.toString(f),transition:p};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Di,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ri(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),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..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ei,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),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:b=>d(n,t.id,{value:b==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.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:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Oi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:p,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id){const O=t.conditions.findIndex(I=>I.id===L.id),M=t.conditions.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&u(t.id,O,M)}},k=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),M=t.groups.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&m(n,O,M)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,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:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),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:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(wn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+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:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=Ni({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=A.useState(!1),k=(D,O,M)=>{const I=y=>y.id===D?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:M,dataType:M.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(D,O=0,M)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.conditions.findIndex(V=>V.id===y.id),z=D.conditions.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&v(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,y)=>e.jsx(wn,{condition:I,index:y,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:p},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.groups.findIndex(V=>V.id===y.id),z=D.groups.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&j(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,O+1,D.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:()=>d(D.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:()=>u(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(Oi,{group:D,depth:O,parentGroupId:M,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:p},D.id),L=Sn(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..."})]}):w(l),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:D=>N(!!D)}),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)"})]})}),C&&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:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&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:u=>{u.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(Fi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function zi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var p;const[o,l]=A.useState(null),c=s.useEditorStore(g=>g.card),i=(p=c==null?void 0:c.config)==null?void 0:p.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),m=A.useCallback(g=>{l(g.active.id)},[]),h=A.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){l(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!Nn(w,E.qualifiedEntityName,i)){Es(),l(null);return}}else{Es(),l(null);return}}const N=n(R);if(Ts(E,N)){l(null);return}const k=s.getNewField(E,R);l(null),r(R,[...N,k]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const k=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Ts(N,S)||r(R,[...S,k]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,k]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(k=>k.id===j),N=E.findIndex(k=>k.id===b);if(S!==N){const k=s.arrayMove(E,S,N);r(C,k)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:m,handleDragEnd:h}}function Pi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(p=>p.isDevMode),o=s.useEditorStore(p=>p.card);s.isExplorerCard(o);const{config:l}=A.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(p=>p.showAIDialog),u=s.useEditorStore(p=>p.frame),m=s.useManagementStore(p=>p.selectedVisual),h=(m==null?void 0:m.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),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($s,{}),n&&!h&&e.jsx(Us,{variant:"default"}),h&&e.jsx(Qr,{}),a&&s.isDevEnv]})]})}function Vi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 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"}),n.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":"Query"})]})})}const _i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Ui(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[o,l]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.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:_i.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function $i({isOpen:t,onClose:a}){const n=Yt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=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(o),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,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:a,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:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function qi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var O;const p=s.useEditorStore(M=>M.card),g=s.useDashboardStore(M=>M.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(M=>M.showAIDialog),[j,b]=A.useState(!1),C=s.useEditorStore(M=>{var I;return((I=M.card.customCardPreferences)==null?void 0:I.url)&&M.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:k}=s.useDashboardCardQuery(u);function w(){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(p.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(g||{},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(u.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...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const L=M=>{if(!p.config)return;if(!M.length){x(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,y=M.map(({id:T,desc:B})=>{var X,K;const z=(X=I.metricColumns)==null?void 0:X.find(_=>_.label===T),V=(K=I.groupByColumns)==null?void 0:K.find(_=>_.label===T),P=z||V;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:B?"desc":"asc"}:null}).filter(T=>T!==null);x(p.id,{...I,sortByColumns:y})},D=A.useMemo(()=>{var M,I;return(I=(M=p.config)==null?void 0:M.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=p.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Pi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),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"&&v&&e.jsx(mn,{variant:"outline"}),e.jsx(Vi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ui,{})}),v&&e.jsx(us,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(hn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!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(Ca,{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:N||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(xn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:D})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(an,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx($i,{isOpen:j,onClose:()=>b(!1)})]})]})}function Yi({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!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 ${a?"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(Cn,{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 Gi=()=>{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 a=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},n=r=>{var o;if((o=r.reason)!=null&&o.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",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var _,$;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);A.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},p=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},v=q=>{m(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:M,setFieldsForContainer:I}=Xs(O),{activeField:y,handleDragStart:T,handleDragEnd:B}=zi({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:M,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},V=q=>{var U;E(q,{config:{...(U=j.cards.find(G=>G.id===q))==null?void 0:U.config,filters:void 0}})},P=k,X=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(G=>{U+=X(G)}),U},K=X(((_=O==null?void 0:O.config)==null?void 0:_.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ui,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(bi,{selectedChart:h,onChartChange:v,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy")}),e.jsx(qi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:p,onAdvancedToggle:g,onFiltersClick:x,filterCount:K,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:M,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&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"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:V,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Yi,{activeField:y||null})})]})}function Qi({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:p,sensors:g}=Or();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function x(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(tn,{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(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})]})}function j(){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(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Ki(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Qi,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),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(Vs,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(tn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Xi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.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)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.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 Zi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function el(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),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:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}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 sl({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(el,{}),e.jsxs("main",{className:"relative flex h-full flex-col",children:[t&&e.jsx(Ir,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Ki,{}),e.jsx(Zi,{})]})]})]})]})})}exports.DashboardPlus=sl;exports.ResourceManagementPanel=en;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Rt;exports.downloadPdf=Ft;exports.getDashbaordStateWithoutData=Bs;