react-semaphor 0.0.575 → 0.0.576

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,4 +1,4 @@
1
- "use strict";var ht=t=>{throw TypeError(t)};var js=(t,n,a)=>n.has(t)||ht("Cannot "+a);var ae=(t,n,a)=>(js(t,n,"read from private field"),a?a.call(t):n.get(t)),_e=(t,n,a)=>n.has(t)?ht("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,a),Ue=(t,n,a,r)=>(js(t,n,"write to private field"),r?r.call(t,a):n.set(t,a),a),$e=(t,n,a)=>(js(t,n,"access private method"),a);const e=require("react/jsx-runtime"),s=require("./index-BRrl9Afb.js"),M=require("react");require("react-dom");function Zn(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const xe=Zn(M);var De,Te,he,be,Ce,as,Ts,Mt,ea=(Mt=class extends s.Subscribable{constructor(n,a){super();_e(this,Ce);_e(this,De);_e(this,Te);_e(this,he);_e(this,be);Ue(this,De,n),this.setOptions(a),this.bindMethods(),$e(this,Ce,as).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var r;const a=this.options;this.options=ae(this,De).defaultMutationOptions(n),s.shallowEqualObjects(this.options,a)||ae(this,De).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ae(this,he),observer:this}),a!=null&&a.mutationKey&&this.options.mutationKey&&s.hashKey(a.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=ae(this,he))==null?void 0:r.state.status)==="pending"&&ae(this,he).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ae(this,he))==null||n.removeObserver(this)}onMutationUpdate(n){$e(this,Ce,as).call(this),$e(this,Ce,Ts).call(this,n)}getCurrentResult(){return ae(this,Te)}reset(){var n;(n=ae(this,he))==null||n.removeObserver(this),Ue(this,he,void 0),$e(this,Ce,as).call(this),$e(this,Ce,Ts).call(this)}mutate(n,a){var r;return Ue(this,be,a),(r=ae(this,he))==null||r.removeObserver(this),Ue(this,he,ae(this,De).getMutationCache().build(ae(this,De),this.options)),ae(this,he).addObserver(this),ae(this,he).execute(n)}},De=new WeakMap,Te=new WeakMap,he=new WeakMap,be=new WeakMap,Ce=new WeakSet,as=function(){var a;const n=((a=ae(this,he))==null?void 0:a.state)??s.getDefaultState();Ue(this,Te,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Ts=function(n){s.notifyManager.batch(()=>{var a,r,l,o,c,i,d,m;if(ae(this,be)&&this.hasListeners()){const u=ae(this,Te).variables,h=ae(this,Te).context;(n==null?void 0:n.type)==="success"?((r=(a=ae(this,be)).onSuccess)==null||r.call(a,n.data,u,h),(o=(l=ae(this,be)).onSettled)==null||o.call(l,n.data,null,u,h)):(n==null?void 0:n.type)==="error"&&((i=(c=ae(this,be)).onError)==null||i.call(c,n.error,u,h),(m=(d=ae(this,be)).onSettled)==null||m.call(d,void 0,n.error,u,h))}this.listeners.forEach(u=>{u(ae(this,Te))})})},Mt);function Pe(t,n){const a=s.useQueryClient(),[r]=xe.useState(()=>new ea(a,t));xe.useEffect(()=>{r.setOptions(t)},[r,t]);const l=xe.useSyncExternalStore(xe.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=xe.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
1
+ "use strict";var ht=t=>{throw TypeError(t)};var js=(t,n,a)=>n.has(t)||ht("Cannot "+a);var ae=(t,n,a)=>(js(t,n,"read from private field"),a?a.call(t):n.get(t)),_e=(t,n,a)=>n.has(t)?ht("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,a),Ue=(t,n,a,r)=>(js(t,n,"write to private field"),r?r.call(t,a):n.set(t,a),a),$e=(t,n,a)=>(js(t,n,"access private method"),a);const e=require("react/jsx-runtime"),s=require("./index-BN1HSp2Z.js"),M=require("react");require("react-dom");function Zn(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const xe=Zn(M);var De,Te,he,be,Ce,as,Ts,Mt,ea=(Mt=class extends s.Subscribable{constructor(n,a){super();_e(this,Ce);_e(this,De);_e(this,Te);_e(this,he);_e(this,be);Ue(this,De,n),this.setOptions(a),this.bindMethods(),$e(this,Ce,as).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var r;const a=this.options;this.options=ae(this,De).defaultMutationOptions(n),s.shallowEqualObjects(this.options,a)||ae(this,De).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ae(this,he),observer:this}),a!=null&&a.mutationKey&&this.options.mutationKey&&s.hashKey(a.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=ae(this,he))==null?void 0:r.state.status)==="pending"&&ae(this,he).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ae(this,he))==null||n.removeObserver(this)}onMutationUpdate(n){$e(this,Ce,as).call(this),$e(this,Ce,Ts).call(this,n)}getCurrentResult(){return ae(this,Te)}reset(){var n;(n=ae(this,he))==null||n.removeObserver(this),Ue(this,he,void 0),$e(this,Ce,as).call(this),$e(this,Ce,Ts).call(this)}mutate(n,a){var r;return Ue(this,be,a),(r=ae(this,he))==null||r.removeObserver(this),Ue(this,he,ae(this,De).getMutationCache().build(ae(this,De),this.options)),ae(this,he).addObserver(this),ae(this,he).execute(n)}},De=new WeakMap,Te=new WeakMap,he=new WeakMap,be=new WeakMap,Ce=new WeakSet,as=function(){var a;const n=((a=ae(this,he))==null?void 0:a.state)??s.getDefaultState();Ue(this,Te,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Ts=function(n){s.notifyManager.batch(()=>{var a,r,l,o,c,i,d,m;if(ae(this,be)&&this.hasListeners()){const u=ae(this,Te).variables,h=ae(this,Te).context;(n==null?void 0:n.type)==="success"?((r=(a=ae(this,be)).onSuccess)==null||r.call(a,n.data,u,h),(o=(l=ae(this,be)).onSettled)==null||o.call(l,n.data,null,u,h)):(n==null?void 0:n.type)==="error"&&((i=(c=ae(this,be)).onError)==null||i.call(c,n.error,u,h),(m=(d=ae(this,be)).onSettled)==null||m.call(d,void 0,n.error,u,h))}this.listeners.forEach(u=>{u(ae(this,Te))})})},Mt);function Pe(t,n){const a=s.useQueryClient(),[r]=xe.useState(()=>new ea(a,t));xe.useEffect(()=>{r.setOptions(t)},[r,t]);const l=xe.useSyncExternalStore(xe.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=xe.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -58,7 +58,7 @@
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const Bs=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"}]]);/**
61
+ */const Fs=s.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
62
62
  * @license lucide-react v0.453.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
@@ -73,7 +73,7 @@
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 Fs=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"}]]);/**
76
+ */const Bs=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"}]]);/**
77
77
  * @license lucide-react v0.453.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
@@ -143,7 +143,7 @@
143
143
  *
144
144
  * This source code is licensed under the ISC license.
145
145
  * See the LICENSE file in the root directory of this source tree.
146
- */const Bt=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"}]]);/**
146
+ */const Ft=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"}]]);/**
147
147
  * @license lucide-react v0.453.0 - ISC
148
148
  *
149
149
  * This source code is licensed under the ISC license.
@@ -198,7 +198,7 @@
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 Be=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"}]]);/**
201
+ */const Fe=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"}]]);/**
202
202
  * @license lucide-react v0.453.0 - ISC
203
203
  *
204
204
  * This source code is licensed under the ISC license.
@@ -233,7 +233,7 @@
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 Ft=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"}]]);/**
236
+ */const Bt=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"}]]);/**
237
237
  * @license lucide-react v0.453.0 - ISC
238
238
  *
239
239
  * This source code is licensed under the ISC license.
@@ -278,12 +278,12 @@
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 Ba=s.createLucideIcon("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
281
+ */const Fa=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"}]]);/**
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 Fa=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
286
+ */const Ba=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
287
287
  * @license lucide-react v0.453.0 - ISC
288
288
  *
289
289
  * This source code is licensed under the ISC license.
@@ -388,7 +388,7 @@
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 Fe=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
391
+ */const Be=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
392
392
  * @license lucide-react v0.453.0 - ISC
393
393
  *
394
394
  * This source code is licensed under the ISC license.
@@ -403,7 +403,7 @@
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 Ka=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ls(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>_t(c))}})}})}}function _t(t){return{...t,customCfg:Qa(t.customCfg),data:[]}}function Qa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Wa(t,n,a,r){if(!r)return null;const l=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:a,operation:"create"})}async function Ms(t,n){if(!n)return null;const{id:a,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Ja(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Xa(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[m,u]=M.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const p=ls(h),y=await Wa(t,p,f,g==null?void 0:g.accessToken);y&&(o([...l||[],y]),c(y.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,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:p=>{n(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,n]=M.useState(!1),a=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(u){o(u)}async function d(u){if(await Ja(u,c==null?void 0:c.accessToken)){const f=a==null?void 0:a.filter(g=>g.id!==u);l(f||[]),o("original")}}async function m(u){const h=a==null?void 0:a.map(j=>j.id===u.id?{...j,isDefault:!u.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...u,isDefault:!u.isDefault};await Ms(f,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==u.id){const j={...g,isDefault:!1};await Ms(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Ut(){var o;const t=s.useDashboardStore.getState().authToken,n=s.useDashboardStore.getState().theme,a=s.useDashboardStore.getState().filterValues,r=(o=s.useDashboardStore.getState().dashboard)==null?void 0:o.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:n||"light",filterValues:a,dashboardTitle:r||"",selectedSheetId:l||""}}async function $t(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:n,theme:a,filterValues:r,dashboardTitle:l,selectedSheetId:o}=Ut();if(t)return;const c=new URLSearchParams;c.set("token",(n==null?void 0:n.accessToken)||""),c.set("theme",a),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",o||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${n==null?void 0:n.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const f=`${l}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function er({iconClassName:t}){const{authToken:n}=s.useSemaphorContext();s.useDashboardStore(l=>{var o;return(o=l.dashboard)==null?void 0:o.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const a=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await $t()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:a?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function fe({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const gt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function qt({triggerButtonClassName:t}){const{data:n,handleScheduleSubscription:a,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=sr(),[i,d]=M.useState(""),[m,u]=M.useState(gt[0].value),[h,f]=M.useState("06:00"),[g,j]=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:p=>d(p.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:g,onChange:p=>{j(p.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(fe,{className:"col-span-2 h-8",label:"Select Frequency",options:gt,value:m,onValueChange:p=>u(p)})]}),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:p=>f(p.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 a({email:i,frequency:m,time:h,subject:g}),f("00:00"),d(""),j("")},className:"h-8 p-2",disabled:l==="loading"||!i,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(Ot,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),n&&n.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:n==null?void 0:n.map(p=>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(p.frequency)," "]}),e.jsx(s.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(jt,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(ua,{className:"size-3.5"})}),e.jsx(jt,{tooltip:`${p.endUserEmail}`,children:e.jsx(La,{className:"size-3.5"})}),c===p.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const jt=({children:t,tooltip:n})=>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:n})]})});function sr(){const[t,n]=M.useState("idle"),[a,r]=M.useState(""),[l,o]=M.useState(null),c=s.useDashboardStore(w=>w.authToken),i=s.useDashboardStore(w=>w.dashboard.id),d=s.useDashboardStore(w=>w.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:m},{data:f,isLoading:g,isError:j,isFetching:p,refetch:y}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function x({email:w,subject:R,frequency:N,time:S}){const{authToken:v,...k}=Ut(),T=Intl.DateTimeFormat().resolvedOptions().timeZone,O={email:w,frequency:N,time:S,timezone:T,endUserId:m,endUserEmail:w,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:k};n("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await s.postRequestRegular(D,(v==null?void 0:v.accessToken)||"",{...O});n("success"),r(""),y(),setTimeout(()=>{n("idle")},2e3)}catch(B){console.error(B),n("error"),r(B.message)}}async function b(w){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(w);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:w}),y(),setTimeout(()=>{o(null)},2e3)}catch(N){console.error(N),o(null),n("error"),r(N.message)}}return{data:f,isLoading:g,isFetching:p,isError:j,isDeleting:l,refetch:y,handleScheduleSubscription:x,handleDeleteSubscription:b,status:t,error:a}}function we(){const{authToken:t,tokenProps:n}=s.useSemaphorContext();let a=null;n&&(n.endUserId&&n.endUserEmail&&n.tenantId?a={id:n.endUserId,name:n.endUserEmail?String(n.displayName):"",email:n.endUserEmail?String(n.endUserEmail):"",type:"tenant",tenantId:n.tenantId}:n.orgUserId&&n.orgUserEmail&&(a={id:n.orgUserId,name:n.orgUserEmail?String(n.displayName):"",email:n.orgUserEmail?String(n.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",a==null?void 0:a.id],queryFn:async()=>{if(!(a!=null&&a.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${a.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)&&!!(a!=null&&a.id)});return{currentUser:a?{...a,...r||{}}:null,isLoading:l,isError:o}}function Yt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}var Z=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(Z||{});const tr=async(t,n,a,r,l,o)=>{const c={},i={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[n]}`,t,c)},nr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}`,t,a)},ar=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},rr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},lr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/duplicate`,t,{})},or=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,t,r)},ir=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},cr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/shares`,t)},dr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,t)};function ur(t){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(n==null?void 0:n.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(n!=null&&n.accessToken):!!(n!=null&&n.accessToken)})}function mr(t,n,a,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=we();return s.useQuery({queryKey:[t,n,a,r,l],queryFn:()=>tr((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function hr(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return Pe({mutationFn:l=>nr((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function Gt(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return Pe({mutationFn:({resourceId:r,data:l})=>ar((n==null?void 0:n.accessToken)||"",t,r,l),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function xr(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return Pe({mutationFn:l=>rr((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function pr(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return Pe({mutationFn:r=>lr((n==null?void 0:n.accessToken)||"",t,r),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.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 fr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:({resourceType:a,resourceId:r,data:l})=>or((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to share resource: ${a.message}`)}})}function gr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:({resourceType:a,resourceId:r,data:l})=>ir((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to remove resource shares: ${a.message}`)}})}function jr(t,n){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,n],queryFn:()=>cr((a==null?void 0:a.accessToken)||"",t,n),enabled:!!(a!=null&&a.accessToken)&&!!n})}function yr(t,n,a){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,n],queryFn:()=>dr((r==null?void 0:r.accessToken)||"",t,n),enabled:(a==null?void 0:a.enabled)!==void 0?a.enabled&&!!(r!=null&&r.accessToken)&&!!n:!!(r!=null&&r.accessToken)&&!!n})}function vr(t,n){return yr(Z.VISUAL,t,n)}function Ht(){const[t,n]=M.useState(new Map),a=M.useCallback((o,c)=>{n(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(o,m),d})},[]),r=M.useCallback((o,c)=>{n(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(o):d.set(o,m),d})},[]),l=M.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:a,stopUpdating:r,isUpdating:l}}function qs(t,n,a){var h;const r=mr(t),l=hr(t,a),o=Gt(t),c=xr(t,n),i=pr(t),d=fr(),m=gr(),u={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function br(t,n){return qs(Z.DASHBOARD,t,n)}function Nr(t,n){return qs(Z.VISUAL,t,n)}function Cr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:async({visualId:a,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function Sr({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var S;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),j=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen),[p,y]=M.useState(!1),[x,b]=M.useState(!1);M.useEffect(()=>{a?(y(!0),b(!0)):x&&(y(!1),b(!1))},[a,x]);const w=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ft,{className:"h-3 w-3 text-purple-500"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Ie,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),N=()=>{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",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:N,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:R()})}),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:v=>i==null?void 0:i(t.id,{title:v}),isEditable:t.ownership.isOwner&&g,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:w()})]}),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:v=>i==null?void 0:i(t.id,{description:v}),isEditable:t.ownership.isOwner&&g,isPending:l,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:v=>{v.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:y,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:v=>v.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:v=>{v.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),m(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Pa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),u(t)},children:[e.jsx(Se,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),d(t),j(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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 Kt({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function os({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(m=>m.value===t))==null?void 0:d.label)||t,i=a.filter(m=>m.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),n(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function Qt({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(os,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function Wt({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Jt({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(m=>m.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(m=>m.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(Se,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function Xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=M.useRef(null);return M.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ge(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function wr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Zt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function kr(t,n,a){const r=Zt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function Dr({user:t}){return Zt(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 Tr({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=wr((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),m=d?d.newRole:n==null?void 0:n.role,u=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(os,{currentRole:m,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ge(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Er({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(We,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function Ir({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function Ar({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],m=c.orgWide||[],u=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,g)=>{var x,b;const j=((x=n.find(w=>w.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((b=n.find(w=>w.id===f.orgUserId))==null?void 0:b.type)||"",y=ge(f.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),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,g)=>{var x,b;const j=((x=n.find(w=>w.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((b=n.find(w=>w.id===f.tenantUserId))==null?void 0:b.type)||"",y=ge(f.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),u.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:u.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),!i.length&&!d.length&&!m.length&&!u.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,m)=>{var g,j;const u=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(p=>p.id===d.tenantUserId))==null?void 0:j.type)||"",f=ge(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},m)}),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,m)=>{const u=ge(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},m)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const m=((f=n.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",u=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=ge(i.role,a(u));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:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const m=ge(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Mr({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function Lr({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?u(t.id):h(t.id):u(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(Dr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(os,{currentRole:n==null?void 0:n.role,onRoleChange:j=>f(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(Tr,{user:t,userShare:n,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(os,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Er,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(Ir,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function en({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),p=c||(N=>{const S=u.some(k=>k.id===N),v=h.includes(N);S?j.removeSelectedUser(N):v?j.removeUserFromRemove(N):j.addSelectedUser({id:N,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,x=d||j.addUserToRemove,b=m||((N,S,v)=>{j.addUserToUpdate({id:N,currentRole:S,newRole:v})}),w=l,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 (",(w??[]).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(Ar,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(w==null?void 0:w.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===w.length?j.setSelectedUsers([]):j.setSelectedUsers(w.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===w.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:n,isSearching:a,searchQuery:g,availableUsers:w||[]}),!n&&!a&&(w==null?void 0:w.length)>0&&w.map(N=>{const S=t?kr(N,t,o):void 0,v=R.includes(N.id),k=!!S,T=k&&!v,O=u.some(E=>E.id===N.id),D=u.find(E=>E.id===N.id),B=r(N.type);return e.jsx(Lr,{user:N,userShare:S,isUserRemoving:v,hasAccess:T,hasAccessFromAPI:k,isSelected:O,selectedUser:D,roleOptions:B,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:b,handleUserRoleChange:y},N.id)})]})]})}function sn({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(Ie,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Me=()=>[{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 Rr({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),m=Me().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),u=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:u,f=n.role!=="NONE"&&!o&&(!l||l.newRole===u),g=l!==null&&l.newRole!==u,j=o,p=u==="NONE"||!u,y=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(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},x=b=>{r(u,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||p?"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(Se,{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"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(j||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||p?"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:m.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(b.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(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 tn({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const m=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:m(n.role)}:{role:"NONE"},f=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,g=(p,y)=>{o(p,y)},j=()=>{c()};return e.jsx(Rr,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:d})}const Or=async(t,n={})=>{const a={};return n.search&&(a.search=n.search),n.type&&(a.type=n.type),n.active!==void 0&&(a.active=n.active.toString()),n.tenantId&&(a.tenantId=n.tenantId),n.limit&&(a.limit=n.limit.toString()),n.offset&&(a.offset=n.offset.toString()),n.page&&(a.page=n.page.toString()),n.pageSize&&(a.pageSize=n.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,a)};function Br(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Or((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Ae(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=Z.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:m}=Br(c),u=jr(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function Fr({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var ee,Q;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[b,w]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:k}=Ae({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:R(),tenantId:N()});M.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,b]);const T=q=>{var $,F;const H=q;if(w(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const _=(F=($=v==null?void 0:v.shares)==null?void 0:$.orgUsersOnly)==null?void 0:F[0];_&&_.role!==void 0&&x.setOrgWideRole(_.role)}},O=S.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),D=S.filter(q=>f.some(H=>H.id===q.id)),B=q=>{var _,Y;const H=f.some(J=>J.id===q),$=g.includes(q),F=(Y=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:Y.some(J=>J.orgUserId===q);H?x.removeSelectedUser(q):$?x.removeUserFromRemove(q):F||x.addSelectedUser({id:q,role:"VIEWER"})},E=(q,H)=>{x.updateSelectedUserRole(q,H)},I=q=>{x.addUserToRemove(q),x.removeSelectedUser(q)},C=q=>{x.removeUserFromRemove(q)},L=q=>{x.removeUserFromUpdate(q)},A=(q,H)=>{x.setOrgWideRole(H)},P=()=>{x.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(Q=(ee=v==null?void 0:v.shares)==null?void 0:ee.orgUsersOnly)==null?void 0:Q[0];M.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&x.setOrgWideRole(V.role)},[b,V,x]);const U=k,W=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(sn,{shareType:b,onShareTypeChange:T,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Ie,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Kt,{value:m,onChange:u}),e.jsx(Qt,{selectedUsers:f,selectedUserObjects:D,onRemove:B,onRoleChange:E,getRoleOptions:Me}),e.jsx(Wt,{usersToRemove:g,allUsers:O,onRemove:C}),e.jsx(Jt,{usersToUpdate:j,allUsers:O,onRemove:L,getRoleOptions:Me}),e.jsx(en,{existingShares:v,isInitialLoading:U,isSearching:W,resource:t,onShare:()=>{},getRoleOptions:Me,allUsers:O,currentUser:a,handleUserToggle:B,handleUserRoleChange:E,handleRemoveAccess:I,handleUpdateAccess:(q,H,$)=>{x.addUserToUpdate({id:q,currentRole:H,newRole:$})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(tn,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:A,onRemoveAccess:P,allUsersToUpdate:p==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:p==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function yt({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var _;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:b,isLoading:w}=ur({enabled:(a==null?void 0:a.type)==="organization"}),[R,N]=M.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,a==null?void 0:a.type]);const S=Y=>{var te,re,ne,ue;N(Y);let J;if(Y==="specific_tenant_users"?J="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?J="all_users":J="specific_users",r==null||r(J),(a==null?void 0:a.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&x.setSelectedTenant(a.tenantId))):(x.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&x.setCurrentMode("allTenants")),Y==="all_tenant_users"){const K=(re=(te=T==null?void 0:T.shares)==null?void 0:te.tenantWide)==null?void 0:re[0];K&&K.role!==void 0&&x.setTenantWideRole(K.role)}else if(Y==="all_tenants"){const K=(ue=(ne=T==null?void 0:T.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:ue[0];K&&K.role!==void 0&&x.setAllTenantsRole(K.role)}},v=Y=>{x.setSelectedTenant(Y)},{allUsers:k,existingShares:T,isLoadingUsers:O,isErrorLoadingUsers:D,isLoadingShares:B,isErrorLoadingShares:E}=Ae({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:y}),I=Y=>{var ne,ue;const J=u.some(K=>K.id===Y),te=h.includes(Y),re=(ue=(ne=T==null?void 0:T.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:ue.some(K=>K.tenantUserId===Y);J?x.removeSelectedUser(Y):te?x.removeUserFromRemove(Y):re||x.addSelectedUser({id:Y,role:"VIEWER"})},C=(Y,J)=>{x.updateSelectedUserRole(Y,J)},L=Y=>{x.addUserToRemove(Y),x.removeSelectedUser(Y)},A=Y=>{x.removeUserFromRemove(Y)},P=Y=>{x.removeUserFromUpdate(Y)},V=(Y,J,te)=>{x.addUserToUpdate({id:Y,currentRole:J,newRole:te})},U=(Y,J)=>{R==="all_tenant_users"?x.setTenantWideRole(J):R==="all_tenants"&&x.setAllTenantsRole(J)},W=()=>{R==="all_tenant_users"?x.setTenantWideRole("VIEWER"):R==="all_tenants"&&x.setAllTenantsRole("VIEWER")},Q=(()=>{var Y,J,te,re;return g==="allTenants"?(J=(Y=T==null?void 0:T.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:J[0]:g==="allTenantUsers"?(re=(te=T==null?void 0:T.shares)==null?void 0:te.tenantWide)==null?void 0:re[0]:null})();M.useEffect(()=>{var Y,J,te,re;if(R==="all_tenant_users"){const ne=(J=(Y=T==null?void 0:T.shares)==null?void 0:Y.tenantWide)==null?void 0:J[0];ne&&ne.role!==void 0&&x.setTenantWideRole(ne.role)}else if(R==="all_tenants"){const ne=(re=(te=T==null?void 0:T.shares)==null?void 0:te.allTenantsOnly)==null?void 0:re[0];ne&&ne.role!==void 0&&x.setAllTenantsRole(ne.role)}},[R,T,x]);const q=k.filter(Y=>u.some(J=>J.id===Y.id)),H=O||B,$=D||E,F=()=>(a==null?void 0:a.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[$&&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"})]})}),!$&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(sn,{shareType:R,onShareTypeChange:S,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(Se,{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(Ie,{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(xt,{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(Ie,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.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:y||"",onValueChange:v,disabled:w,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:w?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(_=b==null?void 0:b.tenants)==null?void 0:_.map(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),F()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Kt,{value:i,onChange:m}),e.jsx(Qt,{selectedUsers:u,selectedUserObjects:q,onRemove:Y=>I(Y),onRoleChange:C,getRoleOptions:Me}),e.jsx(Wt,{usersToRemove:h,allUsers:k,onRemove:A}),e.jsx(Jt,{usersToUpdate:f,allUsers:k,onRemove:P,getRoleOptions:Me}),e.jsx(en,{existingShares:T,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Me,allUsers:k,currentUser:a,handleUserToggle:I,handleUserRoleChange:C,handleRemoveAccess:L,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(tn,{currentUser:a,currentShare:Q,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:U,onRemoveAccess:W,allUsersToUpdate:g==="allTenantUsers"&&((Q==null?void 0:Q.role)===void 0||j!==Q.role)||g==="allTenants"&&((Q==null?void 0:Q.role)===void 0||p!==Q.role)?{currentRole:(Q==null?void 0:Q.role)||"VIEWER",newRole:g==="allTenantUsers"?j:p}:null,allUsersToRemove:g==="allTenantUsers"&&(Q==null?void 0:Q.role)===void 0||g==="allTenants"&&(Q==null?void 0:Q.role)===void 0})}):null}):(a==null?void 0:a.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(xt,{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 nn=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,n,a,r,l,o,c,i,d]),u=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!o)return!1}else if(n==="specificTenantUsers")return o?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0}return!1},[t,n,a,r,l,o]);return{buildShareData:m,validateShareData:u,isCurrentStateValid:h,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function vt({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:b,isCurrentStateValid:w}=nn(),R=a||r||l,N=()=>{var O,D,B,E;if(R)return"Updating...";if(i==="specific_users"){if(u.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=u.length+h.length+f.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&f.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:f.length>0&&u.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 j===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenants";const C=I.role;return p===C?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const C=I.role;return y===C?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(u.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=u.length+h.length+f.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&f.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:f.length>0&&u.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"&&!g||i==="specific_tenant_users"&&!g?!0:!w,v=()=>{const O=x();O&&b(O)&&o(O)},k=()=>{var O,D,B,E;if(i==="all_users")if(!d||d.role===void 0){const I=x();I&&b(I)&&o(I)}else{const I=d.role;if(j===I)m==null||m();else{const L=x();if(L&&b(L)){const A={...L,updateAccess:!0};o(A)}}}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0){const C=x();C&&b(C)&&o(C)}else{const C=I.role;if(p===C)m==null||m();else{const A=x();if(A&&b(A)){const P={...A,updateAccess:!0};o(P)}}}}else if(i==="all_tenant_users"){const I=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!I||I.role===void 0){const C=x();C&&b(C)&&o(C)}else{const C=I.role;if(y===C)m==null||m();else{const A=x();if(A&&b(A)){const P={...A,updateAccess:!0};o(P)}}}}},T=()=>{var O,D,B,E;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return j===I?"destructive":"default"}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const C=I.role;return p===C?"destructive":"default"}else if(i==="all_tenant_users"){const I=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!I||I.role===void 0)return"default";const C=I.role;return y===C?"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:(u.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:v,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(We,{className:"mr-2 h-4 w-4"}),!R&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:T(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Se,{className:"mr-2 h-4 w-4"}),!R&&N()]})]})}function Pr({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=nn(),p=n||a||r,y=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const N=d.length+m.length+u.length;return N===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${N} user${N!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return h===N?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!j,b=()=>{const N=f();N&&g(N)&&l(N)},w=()=>{if(!i||i.role==="NONE"){const N=f();N&&g(N)&&l(N)}else{const N=i.role;if(h===N){const v=f();if(v&&g(v)){const k={...v,removeAccess:!0};l(k)}}else{const v=f();if(v&&g(v)){const k={...v,updateAccess:!0};l(k)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||u.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(We,{className:"mr-2 h-4 w-4"}),!p&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:w,disabled:x(),variant:R(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(We,{className:"mr-2 h-4 w-4"}),!p&&y()]})]})}function an({resource:t,resourceType:n,isSharing:a,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var v,k,T,O;const{currentUser:d}=we(),[m,u]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:y}=Ae({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:x}=Ae({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),b=(k=(v=y==null?void 0:y.shares)==null?void 0:v.tenantWide)==null?void 0:k[0],w=(O=(T=x==null?void 0:x.shares)==null?void 0:T.orgUsersOnly)==null?void 0:O[0],R=()=>{if(j==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},N=M.useCallback(()=>{g.resetShareState(),o()},[g,o]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:N,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(We,{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:j,onValueChange:D=>{const B=D;g.setSelectedTab(B),g.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(Fr,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:f,isSharing:a,isUpdating:l,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(yt,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:D=>u(D),isSharing:a,isUpdating:l,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(yt,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:D=>u(D),isSharing:a,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?j==="org"?e.jsx(vt,{resource:t,existingShares:x,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:w,onRemoveAccess:i}):e.jsx(vt,{resource:t,existingShares:y,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(Pr,{resource:t,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function pe(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ee(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function rn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const f=pe(r,l,m.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(u&&u.length>0){const f=Ee(r,l,u.map(g=>{var p,y;const j=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:y.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:f}=t;if(u&&u.length>0){const g=Ee(r,l,u.map(j=>{var y,x;const p=(x=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:x.find(b=>b.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{d()}})}),m&&m.length>0){const g=pe(r,l,m.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=Ee(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=pe(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else{const m=pe(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const f=pe(r,l,m.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(u&&u.length>0){const f=Ee(r,l,u.map(g=>{var p,y;const j=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:y.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function ln(t,n,a,r){var m,u,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Ee(l,o,t.map(y=>{var b,w;const x=(w=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:w.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const p=n==="tenant"&&a==="allTenants",y=n==="tenant"&&a==="allTenantUsers";if(p){const x=(u=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(x){const b=Ee(l,o,[{scope:"all_tenants_only",role:x.role}]);c(b,{onSuccess:()=>{d()},onError:w=>{console.error("Remove all-tenants access failed:",w)}})}}else if(y){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const b=Ee(l,o,[{scope:"all_tenant_users",role:x.role}]);c(b,{onSuccess:()=>{d()},onError:w=>{console.error("Remove all-tenant-users access failed:",w)}})}}else{const x=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(x){const b=Ee(l,o,[{scope:"org_users_only",role:x.role}]);c(b,{onSuccess:()=>{d()},onError:w=>{console.error("Remove org-wide access failed:",w)}})}}}}function zr(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=we(),{existingShares:d}=Ae({debouncedSearchQuery:"",resourceId:t||"",resourceType:Z.DASHBOARD,userType:"tenant"}),m=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(f=>{if(!t)return;const g={resourceType:Z.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:m};rn(f,g,i)},[t,n,a,d,m,i]),h=M.useCallback(()=>{if(!t)return;const f={resourceType:Z.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:m};ln(l,o||"",c||"",f)},[t,n,a,d,m,l,o,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Vr(t,n,a){const{currentUser:r}=we(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=Ae({debouncedSearchQuery:"",resourceId:t||"",resourceType:Z.VISUAL,userType:"tenant"}),m=M.useCallback(()=>{l.resetUserSelections()},[l]),u=M.useCallback(f=>{if(!t)return;const g={resourceType:Z.VISUAL,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:m};rn(f,g,r)},[t,n,a,d,m,r]),h=M.useCallback(()=>{if(!t)return;const f={resourceType:Z.VISUAL,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:m};ln(o,c||"",i||"",f)},[t,n,a,d,m,o,c,i]);return{handleShareSubmit:u,handleRemoveAccess:h}}function _r(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ys(t){const[n,a]=M.useState(null),[r,l]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Ur(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function bt(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],l=a.getQueryData(r);if(l)return console.log("Using cached visual data for:",n),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",n);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function $r(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function qr(){var f;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ys(((f=a.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),m=s.useEditorStore(g=>g.isShowingVisual),u=a.sql;return{getUpdatedFrame:M.useCallback(()=>{var x;let g=u;u&&!u.includes("{{")&&(g=_r(u),t(g));const j=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:m?a.customCfg:null,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},y=n.cards.map(b=>b.id===a.id?p:b);return{...n,cards:y,activeCardId:Ur(y,n.activeCardId)}},[a,n,m,l,o,c,i,d,t,r,u])}}function Gs(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=vr((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=M.useCallback(async p=>{try{r(p);const{data:y,fromCache:x}=await bt((t==null?void 0:t.accessToken)||"",p.id,n);return $r(y,l,o,c,i),{success:!0,fromCache:x}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,l,o,c,i]),j=M.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:x}=await bt((t==null?void 0:t.accessToken)||"",p.id,n),b=y.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const w={...b,id:s.v4()};return m(h,w,"end"),c(!0),d(w.id),u(!1),{success:!0,fromCache:x}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,m,c,d,u]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:qr().getUpdatedFrame,refetch:f.refetch}}function Yr(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(!1),[u,h]=M.useState(null),[f,g]=M.useState(!1),[j,p]=M.useState(null),[y,x]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:w}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:N}=Gs(),{resources:S,isLoading:v,isError:k,createResource:T,updateResource:O,deleteResource:D,duplicateResource:B,shareResource:E,isCreating:I,isDeleting:C,removeResourceShares:L,isSharing:A,isRemovingShares:P,isUpdatingShares:V}=Nr(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:U,handleRemoveAccess:W}=Vr((u==null?void 0:u.id)||null,E,L);we();const ee=S.filter(z=>{var X,le;return((X=z==null?void 0:z.title)==null?void 0:X.toLowerCase().includes(t.toLowerCase()))||((le=z==null?void 0:z.description)==null?void 0:le.toLowerCase().includes(t.toLowerCase()))}),Q=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&T({title:l,description:c,isPrivate:!1})},H=z=>{p(z),g(!0)},$=()=>{j&&D(j.id)},{startUpdating:F,stopUpdating:_,isUpdating:Y}=Ht(),J=(z,X)=>{const le=X.title!==void 0?"title":"description";F(z,le),O({resourceId:z,data:X},{onSuccess:()=>{_(z,le)},onError:()=>{_(z,le)}})},te=z=>{x(z),B(z,{onSettled:()=>x(null)})},re=z=>{R(z)},ne=z=>{N(z)},ue=z=>{const X=S.find(le=>le.id===z);X&&O({resourceId:z,data:{isPrivate:!X.isPrivate}})},K=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Ae({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:Z.VISUAL,userType:"tenant"}),v?e.jsx(Yt,{}):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:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:z=>o(z.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:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),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:z=>n(z.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:ee.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(xs,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):ee.map(z=>e.jsx(Sr,{visual:z,onAddVisual:ne,onEditVisual:re,onUpdateVisual:J,onDeleteClick:H,onDuplicateVisual:te,onTogglePrivacy:ue,onShareVisual:K,isDeleting:C,isDuplicating:y===z.id,isTitleUpdating:Y(z.id,"title"),isDescriptionUpdating:Y(z.id,"description"),formatDate:Q},z.id))})}),d&&u&&e.jsx(an,{resource:u,resourceType:Z.VISUAL,onShare:U,isSharing:A,isRemoving:P,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:W}),e.jsx(s.AlertDialog,{open:f,onOpenChange:z=>{!z&&C||(g(z),z||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:C,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:C,children:C?"Deleting...":"Delete"})]})]})})]})}function Gr({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:u,onDashboardItemClick:h}){var S;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),[j,p]=M.useState(!1),[y,x]=M.useState(!1),b=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen);M.useEffect(()=>{a?(p(!0),x(!0)):y&&(p(!1),x(!1))},[a,y]);const w=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ft,{className:"h-3 w-3 text-purple-500"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Ie,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),N=()=>{f(t),o(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",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:N,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:R()})}),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:v=>c==null?void 0:c(t.id,{title:v}),isEditable:t.permissions.canEdit&&g,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:w()})]}),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:v=>c==null?void 0:c(t.id,{description:v}),isEditable:t.permissions.canEdit&&g,isPending:l,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:j,onOpenChange:p,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:v=>v.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:v=>{v.preventDefault(),v.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),m(t)},children:[e.jsx(Se,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t),b(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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:u(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Hr({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 Kr(t){const[n,a]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[m,u]=M.useState(!1),[h,f]=M.useState(null),[g,j]=M.useState(!1),[p,y]=M.useState(null),[x,b]=M.useState(null),w=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:N,isLoading:S,isError:v,createResource:k,updateResource:T,deleteResource:O,duplicateResource:D,isCreating:B,isDeleting:E,isSharing:I,isRemovingShares:C,isUpdatingShares:L,shareResource:A,removeResourceShares:P}=br(()=>{j(!1),y(null),w&&R(w)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:U}=zr((h==null?void 0:h.id)||null,A,P),{currentUser:W}=we(),ee=N.filter(K=>{var z,X;return((z=K==null?void 0:K.title)==null?void 0:z.toLowerCase().includes(n.toLowerCase()))||((X=K==null?void 0:K.description)==null?void 0:X.toLowerCase().includes(n.toLowerCase()))}),Q=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&k({title:o,description:i,isPrivate:!1})},H=K=>{var z;(z=t.onLoadDashboard)==null||z.call(t,K)},$=K=>{y(K),j(!0)},F=()=>{p&&O(p.id)},_=K=>{b(K),D(K,{onSettled:()=>b(null)})},{startUpdating:Y,stopUpdating:J,isUpdating:te}=Ht(),re=(K,z)=>{const X=z.title!==void 0?"title":"description";Y(K,X),T({resourceId:K,data:z},{onSuccess:()=>{J(K,X)},onError:()=>{J(K,X)}})},ne=K=>{const z=N.find(X=>X.id===K);z&&T({resourceId:K,data:{isPrivate:!z.isPrivate}})},ue=K=>{f(K),W==null||W.type,u(!0)};return Ae({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:Z.DASHBOARD,userType:"tenant"}),S?e.jsx(Yt,{}):v?e.jsx(Hr,{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:o,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:q,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||B,children:B?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:B,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:B,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),B?"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:n,onChange:K=>a(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:ee.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ba,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):ee.map(K=>e.jsx(Gr,{dashboard:K,isDeleting:E,isDuplicating:x===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:H,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:$,onDuplicateDashboard:_,onTogglePrivacy:ne,onShareDashboard:ue,formatDate:Q,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),m&&h&&e.jsx(an,{resource:h,resourceType:Z.DASHBOARD,onShare:V,isSharing:I,isRemoving:C,isUpdating:L,onClose:()=>{u(!1),f(null)},onRemoveAccess:U}),e.jsx(s.AlertDialog,{open:g,onOpenChange:K=>{!K&&E||(j(K),K||y(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 "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:E,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),F()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:E,children:E?"Deleting...":"Delete"})]})]})})]})}function on({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(g=>g.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(g=>g.actions),{currentUser:c}=we(),i=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Xt(n,{enabled:t}),h=g=>{},f=g=>{console.log("Editing dashboard:",g)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",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:n,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:m,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(Kr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Yr,{})})]})})]})})}function Qr(){var H,$;const{authToken:t,tokenProps:n}=s.useSemaphorContext();s.useDashboardStore(F=>F.theme);const a=s.useDashboardStore(F=>F.lenses),r=s.useDashboardStore(F=>F.selectedLensId),l=a==null?void 0:a.find(F=>F.id===r),o=s.useDashboardStore(F=>F.dashboard);s.useDashboardStore(F=>F.selectedSheetId);const c=s.useDashboardStore(F=>F.isDashboardEditing),i=s.useEditorStore(F=>F.card),d=s.useEditorStore(F=>F.selectedConnectionId),[m,u]=M.useState(!1),h=s.useDashboardStore(F=>F.isDashboardPanelOpen),f=s.useDashboardStore(F=>F.actions.setIsDashboardPanelOpen),g=s.useDashboardStore(F=>F.filterValues),j=s.useDashboardStore(F=>F.isVisualEditing),p=s.useManagementStore(F=>F.selectedDashboard),y=s.useManagementStore(F=>F.initialDashboard),x=p?($=p==null?void 0:p.permissions)==null?void 0:$.canEdit:(H=y==null?void 0:y.permissions)==null?void 0:H.canEdit,b=s.useDashboardStore(F=>F.showFilters);s.useDashboardStore(F=>F.showDashboardJSON);const w=s.useDashboardStore(F=>F.onSaveFunction),R=s.useDashboardStore(F=>F.actions.setShowFilters),{addFrame:N,setSelectedFrameId:S}=s.useDashboardStore(F=>F.actions),{getSelectedSheet:v,setIsDashboardEditing:k,setShowDashboardJSON:T}=s.useDashboardStore(F=>F.actions),O=v(),{setInitialDashboard:D}=s.useManagementStore(F=>F.actions),{resources:B}=qs(Z.DASHBOARD);M.useEffect(()=>{if(B&&B.length>0){const F=o==null?void 0:o.id;if(F){const _=B.find(Y=>Y.id===F);_&&D(_)}}},[B,o==null?void 0:o.id,D]);const E=n.orgUserId||n.tenantId,I=c&&!j&&E&&x;function C(){var J,te;const F=i.dataSource;if(F)return F;const _=(te=(J=o.aiContext)==null?void 0:J.selectedEntities)==null?void 0:te[0],Y=_==null?void 0:_.type;if(_)return{connectionId:_.connectionId,connectionType:_.connectionType,type:Y,selectedEntities:[_]}}const L=()=>{if(!c||!O)return;const _={dataSource:C(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},Y={id:s.v4(),cards:[_],activeCardId:_.id};N(O.id,Y),S(Y.id)},A=()=>{k(!0)},[P,V]=M.useState(!1),U=Gt(Z.DASHBOARD);async function W(){const F=ls(o);V(!0);const _={template:F};U.mutate({resourceId:F.id,data:_},{onSuccess:()=>{V(!1),s.ue.success("Dashboard saved!")},onError:()=>{V(!1),s.ue.error("Failed to save dashboard")}})}async function ee(){if(u(!0),!r||!l)return;const F=ls(o),_=JSON.stringify(F),Y={...l,template:_,filterValues:g};await Ms(Y,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),w==null||w(F),u(!1)}if(j)return null;const Q=(l==null?void 0:l.name)||o.title,q=n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[q&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ka,{className:"h-4 w-4"})}),!j&&e.jsx(s.Label,{children:Q})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!j&&e.jsx(er,{}),!j&&e.jsx(qt,{}),c&&!j&&E&&e.jsx(Xa,{}),!j&&E&&e.jsx(Za,{}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:L,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!j&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:A,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{k(!1),T(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!j&&E&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:ee,size:"sm",children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),I&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:P,onClick:W,size:"sm",children:[P?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(As,{className:"mr-2 h-4 w-4"}),P?"Saving...":"Save"]}),!b&&!j&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>R(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!j&&c&&!1,!j&&!1,!j&&e.jsx(on,{isOpen:h,onClose:()=>f(!1)})]})]})}function Wr({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const u=xe.useRef(null),[h,f]=xe.useState(!1),[g,j]=xe.useState("100%"),p=m?[...n||[],{id:"none",name:"None"}]:n;xe.useLayoutEffect(()=>{u.current&&j(u.current.offsetWidth)},[]);function y(){var b;return l?"Loading...":o?"Error":a?(b=n==null?void 0:n.find(w=>w.id===a))==null?void 0:b.name:`Select ${t}`}function x(b,w){r(w),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,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:y()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Pt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:w=>x(w,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function qe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":l?"Error":a;function f(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(Ye,{className:"size-4"});if(t==="Model")return e.jsx(ia,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:m,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...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Pt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,y)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Wr,{icon:f(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:u==="select"?g():j()})})}function Jr({column:t}){const[n,a]=M.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:m}=s.useEditorAside(),u=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,y){var R;const x=s.createSqlGenConfig(p,i,y),b=(R=d==null?void 0:d.find(N=>N.id===c))==null?void 0:R.name;u(x);const w=s.getSql(x,s.fmt(l||""),s.fmt(r),b||"",m,o||"");w&&(h(w),f(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function Hs({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(Be,{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(Je,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ca,{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 ys({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",n),children:[e.jsx(Hs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Xr({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Zr({onClick:t,column:n}){const a=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return i(u)||d(u)||m(u)}function i(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return l==null?void 0:l.some(h=>h.name===u.column_name)}function m(u){return o==null?void 0:o.some(h=>h.name===u.column_name)}return e.jsxs("div",{onClick:()=>t(n),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(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ys,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ys,{column:n})}),e.jsx(Xr,{id:n.column_name,type:"column",children:e.jsx(ys,{column:n})})]})}const vs={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},Ns={id:"__placeholder__",role:"metric",type:"number"},Cs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},cn={id:"__placeholder__"},Le="droppable-group-by",Re="droppable-metrics",Oe="droppable-pivot-by",is="sortable-group-by",Ls="sortable-metrics",cs="sortable-pivot-by",Rs="droppable-filters",Os="sortable-filters",Ks="sortable-order-by";function el(){const t=s.useDndStore(I=>I.insertIndex),n=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.groupByColumns)||[]}),a=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.metricColumns)||[]}),r=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.filterColumns)||[]}),l=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.orderBy)||[]}),o=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:p,setPivotByColumns:y}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),w=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var A;const{active:C,over:L}=I;if(((A=C.data.current)==null?void 0:A.type)==="column"&&L){const P=L.id,V=x.find(Q=>Q.column_name===C.id);if(!V)return;const U=s.isNumberDataType(V.data_type),W=s.isTextDataType(V.data_type),ee=s.isDateDataType(V.data_type);if(W||ee){if(n.some(q=>q.id===P)){const q=n.findIndex($=>$.id===P);c(q);const H=n.filter($=>$.id!==vs.id);H.splice(q,0,vs),d(H)}else if(L.id===Le){c(n.length);const q=[...n,vs];d(q),m(a),u(r)}}if(W||ee){if(o.some(q=>q.id===P)){const q=o.findIndex($=>$.id===P);c(q);const H=o.filter($=>$.id!==bs.id);H.splice(q,0,bs),h(H)}else if(L.id===Oe){c(o.length);const q=[...o,bs];h(q),d(n),m(a),u(r)}}if(U||W){if(a.some(q=>q.id===P)){console.log("isOverMetricSortable",P);const q=a.findIndex($=>$.id===P);c(q);const H=a.filter($=>$.id!==Ns.id);H.splice(q,0,Ns),m(H)}else if(L.id===Re){c(a.length);const q=[...a,Ns];m(q),u(r),d(n),h(o)}}if(S(V)){if(r.some(q=>q.id===P)){const q=r.findIndex($=>$.id===P);c(q);const H=r.filter($=>$.id!==Cs.id);H.splice(q,0,Cs),u(H)}else if(L.id===Rs){c(r.length);const q=[...r,Cs];u(q),m(a),d(n),h(o)}}}else d(n),m(a),u(r),h(o)};function N(I){i(I.active.id),c(null),d(n),m(a),u(r),h(o)}function S(I){return!r.some(C=>C.name===I.column_name)}function v(I,C="SUM"){const{column_name:L,data_type:A}=I,P=[...a],V=t!==null?t:a.length,U={...I,id:je(L),name:L,label:Xe(L,C),type:A,role:"metric",aggregate:C};P.splice(V,0,U),g(P)}function k(I){const C=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const L=[...o],A=t!==null?t:o.length;let P;C?P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ge(I.column_name,"month"),granularity:"month"},L.splice(A,0,P),y(L)}function T(I){const C=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const L=[...n],A=t!==null?t:n.length;let P;C?P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ge(I.column_name,"month"),granularity:"month"},L.splice(A,0,P),f(L)}function O(I){const C=[...r],L=t!==null?t:r.length,A={...I,id:je(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"};C.splice(L,0,A),j(C)}function D(I){var P,V,U,W,ee,Q,q,H;const{active:C,over:L}=I,A=C.data.current;if((A==null?void 0:A.type)==="column"&&L){const $=x.find(J=>J.column_name===C.id);if(!$)return;const F=s.isNumberDataType($.data_type),_=s.isTextDataType($.data_type),Y=s.isDateDataType($.data_type);(_||Y)&&(L.id===Le||((P=L.data.current)==null?void 0:P.type)===is)&&T($),(_||Y)&&(L.id===Oe||((V=L.data.current)==null?void 0:V.type)===cs)?k($):(F||_)&&(L.id===Re||((U=L.data.current)==null?void 0:U.type)===Ls)?(F&&v($),_&&v($,"COUNT")):S($)&&(L.id===Rs||((W=L.data.current)==null?void 0:W.type)===Os)&&O($)}if(L&&((ee=L.data.current)==null?void 0:ee.type)===is&&n.some($=>$.id===C.id)){const $=n.findIndex(_=>_.id===C.id),F=n.findIndex(_=>_.id===L.id);if($!==-1&&F!==-1&&$!==F){const _=[...n],[Y]=_.splice($,1);_.splice(F,0,Y),f(_)}}if(L&&((Q=L.data.current)==null?void 0:Q.type)===cs&&o.some($=>$.id===C.id)){const $=o.findIndex(_=>_.id===C.id),F=o.findIndex(_=>_.id===L.id);if($!==-1&&F!==-1&&$!==F){const _=[...o],[Y]=_.splice($,1);_.splice(F,0,Y),y(_)}}if(L&&((q=L.data.current)==null?void 0:q.type)===Ls&&a.some($=>$.id===C.id)){const $=a.findIndex(_=>_.id===C.id),F=a.findIndex(_=>_.id===L.id);if($!==-1&&F!==-1&&$!==F){const _=[...a],[Y]=_.splice($,1);_.splice(F,0,Y),g(_)}}if(L&&((H=L.data.current)==null?void 0:H.type)===Os&&r.some($=>$.id===C.id)){const $=r.findIndex(_=>_.id===C.id),F=r.findIndex(_=>_.id===L.id);if($!==-1&&F!==-1&&$!==F){const _=[...r],[Y]=_.splice($,1);_.splice(F,0,Y),j(_)}}B(I),i(null),c(null),d(n),m(a),u(r),h(o)}function B(I){const{active:C,over:L}=I,A=C.data.current;if((A==null?void 0:A.type)===Ks&&L){const P=l.findIndex(U=>Ke(U.columnId)===C.id),V=l.findIndex(U=>Ke(U.columnId)===L.id);if(P!==-1&&V!==-1&&P!==V){const U=[...l],[W]=U.splice(P,1);U.splice(V,0,W),p(U)}}}function E(){i(null),c(null),d(n),m(a),u(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:N,handleDragCancel:E,sensors:w}}function je(t){return`${t}-${s.v4()}`}function Xe(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ke(t){return`${Ks}-${t}`}function Ge(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function sl({schemaName:t,tableName:n,columns:a,status:r}){const l=s.useEditorStore(C=>C.sqlGen),o=s.useEditorStore(C=>C.isDevMode),c=s.useEditorStore(C=>C.selectedConnectionId),i=s.useEditorStore(C=>{var L,A;return(A=(L=C.card)==null?void 0:L.queryConfig)==null?void 0:A.metricColumns});s.useEditorStore(C=>{var L,A;return(A=(L=C.card)==null?void 0:L.queryConfig)==null?void 0:A.groupByColumns});const d=s.useEditorStore(C=>C.selectedDatabaseName),m=s.useEditorStore(C=>C.selectedSchemaName),u=s.useEditorStore(C=>C.selectedTableName),h=s.useEditorStore(C=>C.selectedDatamodelId),f=s.useDashboardStore(C=>C.dashboard.aiScopeTables),{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:y,setCardSql:x,setRunSql:b,setSqlGen:w,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:N,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function k(C){var L;if(o){const A=s.createSqlGenConfig(C,l);w(A);const P=(L=S==null?void 0:S.find(U=>U.id===h))==null?void 0:L.name,V=s.getSql(A,s.fmt(t),s.fmt(n),P||"",N,d||"");V&&(x(V),b(!0))}if(!o){if(s.isTextDataType(C.data_type))if(i&&i.length>0){const A={...C,role:"groupby",id:je(C.column_name),name:C.column_name,type:C.data_type};y(A)}else{const A={...C,role:"metric",id:je(C.column_name),name:C.column_name,label:Xe(C.column_name,"COUNT"),type:C.data_type,aggregate:"COUNT"};p(A)}if(s.isDateDataType(C.data_type)){const A={...C,role:"groupby",id:je(C.column_name),name:C.column_name,type:C.data_type,label:Ge(C.column_name,"month"),granularity:"month"};y(A)}if(s.isNumberDataType(C.data_type)){const A={...C,role:"metric",id:je(C.column_name),name:C.column_name,label:Xe(C.column_name,"SUM"),type:C.data_type,aggregate:"SUM"};p(A)}}}function T(C){C===!0&&(u||v)&&c?(g({connectionId:c,connectionType:N==="S3"||N==="API"?"DuckDb":N||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:N||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function O(){const C=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:d||""});R(!1);const L=N==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;x(L),b(!0)}function D(){const C=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${C}`),b(!0)}function B(){return(f==null?void 0:f.find(C=>C.connectionId===c&&(C.tableName===u||C.datamodelName===v)))!==void 0}function E(C){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(C),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hs,{column:C}),e.jsx("span",{children:C.column_name})]}),e.jsx("div",{onClick:L=>L.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(C.data_type)&&e.jsx(Jr,{column:C})})]}):e.jsx(Zr,{onClick:k,column:C})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:T,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,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(Ma,{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(zt,{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((C,L)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},L))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[o&&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:a==null?void 0:a.map(C=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:E(C)},C.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function dn({ColumnsComponent:t,type:n}){var ve;const a=s.useEditorStore(se=>se.card),r=s.useEditorStore(se=>se.selectedConnectionId),l=s.useDashboardStore(se=>se.showFilters),o=s.useEditorStore(se=>se.selectedDatamodelId),c=s.useEditorStore(se=>se.selectedDatabaseName),i=s.useEditorStore(se=>se.selectedSchemaName),d=s.useEditorStore(se=>se.selectedTableName),m=s.useEditorStore(se=>se.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:g,modelItems:j,schemaItems:p,databaseItems:y,tableItems:x,columns:b,isConnectionsLoading:w,isModelsLoading:R,isConnectionsError:N,isModelsError:S,isDatabasesLoadingOrFetching:v,isDatabaseError:k,isSchemaLoadingOrFetching:T,isSchemaError:O,isColumnsError:D,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:E,isTableError:I,connectionType:C,isNonDbConnection:L,refetchDatabases:A,refetchModels:P,refetchSchemas:V,refetchTables:U,refetchColumns:W,refetchConnections:ee,handleConnectionChange:Q,handleDatabaseChange:q,handleSchemaChange:H,handleDatamodelChange:$,handleTableChange:F,tableName:_,schemaName:Y}=s.useEditorAside(),{data:J,refetch:te}=s.useDashboardCardQuery(a);function re(){return t?t(Y,_,b):e.jsx(sl,{schemaName:Y,tableName:_,columns:b,status:B?"Loading...":D?"Error":"Success"})}function ne(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ue(se){se===!0?J&&(f(J.userSql),setTimeout(()=>{te()},100)):f(""),h(se)}function K(){if(!r||C==="S3"||C==="API")return null;if(!o||o==="none")return e.jsx(qe,{refetch:A,showNone:!0,onChange:q,isError:k,isLoading:v,items:y,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!L&&(!c||c==="none")&&(!o||o==="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 X(){if(!r||C==="S3"||C==="API")return null;if(!c||c==="none")return e.jsx(qe,{refetch:P,showNone:!0,onChange:$,isError:S,isLoading:R,items:j,value:o||"",title:"Model",type:"combobox"})}function le(){return!r||C==="S3"||C==="API"||!c||c==="none"?null:e.jsx(qe,{refetch:V,onChange:H,isError:O,isLoading:T,items:p,value:i||"",title:"Schema",type:"combobox"})}function ye(){function se(){let ce=!1;return C==="API"?(ce=!1,ce):((C==="S3"||r&&c&&c!=="none"&&i)&&(ce=!0),ce)}return se()?e.jsx(qe,{refetch:U,onChange:F,isError:I,items:x,isLoading:E,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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(qe,{refetch:ee,items:g,title:"Connection",value:r||"",onChange:Q,isLoading:w,isError:N,type:"combobox",connectionTooltip:((ve=g==null?void 0:g.find(se=>se.id===r))==null?void 0:ve.type)||""}),K(),z(),X(),le(),ye()]}),re(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:ue,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ne,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ra,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function un({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function m(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function u(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:m,onMouseUp:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function mn({sql:t,error:n,onDebugWithAssistant:a}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:o,setRunSql:c}=s.useEditorActions();function i(){l(!r),o(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:[n&&e.jsx(un,{error:n}),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(ga,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&a&&e.jsxs(s.Button,{onClick:a,size:"sm",variant:"secondary",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function hn({sql:t,error:n,onDebugWithAssistant:a}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Ot,{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(mn,{sql:t,error:n,onDebugWithAssistant:a})})]})}var xn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Nt=M.createContext&&M.createContext(xn),tl=["attr","size","title"];function nl(t,n){if(t==null)return{};var a=al(t,n),r,l;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(l=0;l<o.length;l++)r=o[l],!(n.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(a[r]=t[r])}return a}function al(t,n){if(t==null)return{};var a={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(n.indexOf(r)>=0)continue;a[r]=t[r]}return a}function ds(){return ds=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},ds.apply(this,arguments)}function Ct(t,n){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);n&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),a.push.apply(a,r)}return a}function us(t){for(var n=1;n<arguments.length;n++){var a=arguments[n]!=null?arguments[n]:{};n%2?Ct(Object(a),!0).forEach(function(r){rl(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Ct(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function rl(t,n,a){return n=ll(n),n in t?Object.defineProperty(t,n,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[n]=a,t}function ll(t){var n=ol(t,"string");return typeof n=="symbol"?n:n+""}function ol(t,n){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,n);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(t)}function pn(t){return t&&t.map((n,a)=>M.createElement(n.tag,us({key:a},n.attr),pn(n.child)))}function ze(t){return n=>M.createElement(il,ds({attr:us({},t.attr)},n),pn(t.child))}function il(t){var n=a=>{var{attr:r,size:l,title:o}=t,c=nl(t,tl),i=l||a.size||"1em",d;return a.className&&(d=a.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ds({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,r,c,{className:d,style:us(us({color:t.color||a.color},a.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),o&&M.createElement("title",null,o),t.children)};return Nt!==void 0?M.createElement(Nt.Consumer,null,a=>n(a)):n(xn)}function cl(t){return ze({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 fn(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:m}=s.useEditorActions(),u=M.useRef(),h=M.useRef({}),f=r.cards.find(p=>p.id===o),g=M.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(u.current&&c){const p=u.current.getModel();p&&(h.current[l.id]=p);let y=h.current[o];if(!y){const x=g();y=c.editor.createModel(x,t),h.current[o]=y}u.current.setModel(y)}d(o,l),m(!0)}},[o,l,d,c,m,t,g]),M.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?p:a;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),M.useEffect(()=>{const p=u.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(p,y){if(u.current=p,!h.current[l.id]){const x=p.getModel(),b=g();h.current[l.id]=x||(y==null?void 0:y.editor.createModel(b,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function dl(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=fn("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ul(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=fn("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function ml({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 Qs({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ys(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Gs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function hl(){const t=s.useQueryClient(),[n,a]=M.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Gs(),c=s.useSelectedVisual(),i=Cr(),d=()=>{const m=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:m}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ws(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:m}=r;d&&m&&a.setQueryData(d,m)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ps(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:m,setCardPreferences:u,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function p(){const y=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),m(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function xl(){const t=s.useQueryClient(),[n,a]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(U=>U.frame);const o=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.isShowingVisual),s.useEditorStore(U=>U.selectedConnectionId),s.useEditorStore(U=>U.tempQueryData),s.useEditorStore(U=>U.selectedDatabaseName),s.useEditorStore(U=>U.selectedDatamodelId),s.useEditorStore(U=>U.selectedSchemaName);const c=s.useEditorStore(U=>U.showAIDialog);s.useEditorStore(U=>U.selectedTableName);const i=s.useEditorStore(U=>{var W;return(W=U==null?void 0:U.card)==null?void 0:W.sql}),d=s.useEditorStore(U=>{var W;return(W=U==null?void 0:U.card)==null?void 0:W.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:p,setCardType:y,setCardPython:x,runAssistant:b,setShowAIDialog:w}=s.useEditorActions();s.useEditorStore(U=>U.onSave),s.useEditorStore(U=>U.onClose),s.useEditorStore(U=>U.actions.setSqlGen);const R=s.useEditorStore(U=>U.runSql),N=s.useEditorStore(U=>U.actions.setRunSql),S=s.useEditorStore(U=>U.actions.setIsSqlRunning),{data:v,isLoading:k,isFetching:T,isSuccess:O,isError:D,error:B,queryKey:E,refetch:I,errorMessage:C}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:U}=s.getKeys(v.records);h(U)}},[v,h,j]),M.useEffect(()=>{(k||T)&&S(!0),(D||O)&&S(!1),D&&(h([]),j(""))},[k,T,v,j,D,O,S,h,B]),M.useEffect(()=>{R&&(t.getQueryData(E)||I(),N(!1))},[R,I,N,E,t]);async function L(){const U=`Can you help me debug this query in the current table scope?
406
+ */const Ka=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ls(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>_t(c))}})}})}}function _t(t){return{...t,customCfg:Qa(t.customCfg),data:[]}}function Qa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Wa(t,n,a,r){if(!r)return null;const l=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:a,operation:"create"})}async function Ms(t,n){if(!n)return null;const{id:a,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Ja(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Xa(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[m,u]=M.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const p=ls(h),y=await Wa(t,p,f,g==null?void 0:g.accessToken);y&&(o([...l||[],y]),c(y.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,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:p=>{n(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,n]=M.useState(!1),a=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(u){o(u)}async function d(u){if(await Ja(u,c==null?void 0:c.accessToken)){const f=a==null?void 0:a.filter(g=>g.id!==u);l(f||[]),o("original")}}async function m(u){const h=a==null?void 0:a.map(j=>j.id===u.id?{...j,isDefault:!u.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...u,isDefault:!u.isDefault};await Ms(f,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==u.id){const j={...g,isDefault:!1};await Ms(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Ut(){var o;const t=s.useDashboardStore.getState().authToken,n=s.useDashboardStore.getState().theme,a=s.useDashboardStore.getState().filterValues,r=(o=s.useDashboardStore.getState().dashboard)==null?void 0:o.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:n||"light",filterValues:a,dashboardTitle:r||"",selectedSheetId:l||""}}async function $t(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:n,theme:a,filterValues:r,dashboardTitle:l,selectedSheetId:o}=Ut();if(t)return;const c=new URLSearchParams;c.set("token",(n==null?void 0:n.accessToken)||""),c.set("theme",a),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",o||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${n==null?void 0:n.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const f=`${l}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function er({iconClassName:t}){const{authToken:n}=s.useSemaphorContext();s.useDashboardStore(l=>{var o;return(o=l.dashboard)==null?void 0:o.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const a=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await $t()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:a?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function fe({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const gt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function qt({triggerButtonClassName:t}){const{data:n,handleScheduleSubscription:a,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=sr(),[i,d]=M.useState(""),[m,u]=M.useState(gt[0].value),[h,f]=M.useState("06:00"),[g,j]=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:p=>d(p.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:g,onChange:p=>{j(p.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(fe,{className:"col-span-2 h-8",label:"Select Frequency",options:gt,value:m,onValueChange:p=>u(p)})]}),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:p=>f(p.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 a({email:i,frequency:m,time:h,subject:g}),f("00:00"),d(""),j("")},className:"h-8 p-2",disabled:l==="loading"||!i,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(Ot,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),n&&n.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:n==null?void 0:n.map(p=>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(p.frequency)," "]}),e.jsx(s.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(jt,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(ua,{className:"size-3.5"})}),e.jsx(jt,{tooltip:`${p.endUserEmail}`,children:e.jsx(La,{className:"size-3.5"})}),c===p.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const jt=({children:t,tooltip:n})=>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:n})]})});function sr(){const[t,n]=M.useState("idle"),[a,r]=M.useState(""),[l,o]=M.useState(null),c=s.useDashboardStore(k=>k.authToken),i=s.useDashboardStore(k=>k.dashboard.id),d=s.useDashboardStore(k=>k.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:m},{data:f,isLoading:g,isError:j,isFetching:p,refetch:y}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function x({email:k,subject:R,frequency:b,time:S}){const{authToken:v,...E}=Ut(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,O={email:k,frequency:b,time:S,timezone:w,endUserId:m,endUserEmail:k,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:E};n("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const F=await s.postRequestRegular(D,(v==null?void 0:v.accessToken)||"",{...O});n("success"),r(""),y(),setTimeout(()=>{n("idle")},2e3)}catch(F){console.error(F),n("error"),r(F.message)}}async function N(k){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(k);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:k}),y(),setTimeout(()=>{o(null)},2e3)}catch(b){console.error(b),o(null),n("error"),r(b.message)}}return{data:f,isLoading:g,isFetching:p,isError:j,isDeleting:l,refetch:y,handleScheduleSubscription:x,handleDeleteSubscription:N,status:t,error:a}}function we(){const{authToken:t,tokenProps:n}=s.useSemaphorContext();let a=null;n&&(n.endUserId&&n.endUserEmail&&n.tenantId?a={id:n.endUserId,name:n.endUserEmail?String(n.displayName):"",email:n.endUserEmail?String(n.endUserEmail):"",type:"tenant",tenantId:n.tenantId}:n.orgUserId&&n.orgUserEmail&&(a={id:n.orgUserId,name:n.orgUserEmail?String(n.displayName):"",email:n.orgUserEmail?String(n.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",a==null?void 0:a.id],queryFn:async()=>{if(!(a!=null&&a.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${a.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)&&!!(a!=null&&a.id)});return{currentUser:a?{...a,...r||{}}:null,isLoading:l,isError:o}}function Yt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}var Z=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(Z||{});const tr=async(t,n,a,r,l,o)=>{const c={},i={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[n]}`,t,c)},nr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}`,t,a)},ar=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},rr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},lr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/duplicate`,t,{})},or=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,t,r)},ir=async(t,n,a,r)=>{const l={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},cr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/shares`,t)},dr=async(t,n,a)=>{const r={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,t)};function ur(t){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(n==null?void 0:n.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(n!=null&&n.accessToken):!!(n!=null&&n.accessToken)})}function mr(t,n,a,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=we();return s.useQuery({queryKey:[t,n,a,r,l],queryFn:()=>tr((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function hr(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return Pe({mutationFn:l=>nr((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function Gt(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return Pe({mutationFn:({resourceId:r,data:l})=>ar((n==null?void 0:n.accessToken)||"",t,r,l),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function xr(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return Pe({mutationFn:l=>rr((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function pr(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return Pe({mutationFn:r=>lr((n==null?void 0:n.accessToken)||"",t,r),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.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 fr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:({resourceType:a,resourceId:r,data:l})=>or((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to share resource: ${a.message}`)}})}function gr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:({resourceType:a,resourceId:r,data:l})=>ir((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to remove resource shares: ${a.message}`)}})}function jr(t,n){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,n],queryFn:()=>cr((a==null?void 0:a.accessToken)||"",t,n),enabled:!!(a!=null&&a.accessToken)&&!!n})}function yr(t,n,a){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,n],queryFn:()=>dr((r==null?void 0:r.accessToken)||"",t,n),enabled:(a==null?void 0:a.enabled)!==void 0?a.enabled&&!!(r!=null&&r.accessToken)&&!!n:!!(r!=null&&r.accessToken)&&!!n})}function vr(t,n){return yr(Z.VISUAL,t,n)}function Ht(){const[t,n]=M.useState(new Map),a=M.useCallback((o,c)=>{n(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(o,m),d})},[]),r=M.useCallback((o,c)=>{n(i=>{const d=new Map(i),m=new Set(d.get(o)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(o):d.set(o,m),d})},[]),l=M.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:a,stopUpdating:r,isUpdating:l}}function qs(t,n,a){var h;const r=mr(t),l=hr(t,a),o=Gt(t),c=xr(t,n),i=pr(t),d=fr(),m=gr(),u={[Z.DASHBOARD]:"dashboards",[Z.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function br(t,n){return qs(Z.DASHBOARD,t,n)}function Nr(t,n){return qs(Z.VISUAL,t,n)}function Cr(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return Pe({mutationFn:async({visualId:a,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function Sr({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var S;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),j=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen),[p,y]=M.useState(!1),[x,N]=M.useState(!1);M.useEffect(()=>{a?(y(!0),N(!0)):x&&(y(!1),N(!1))},[a,x]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bt,{className:"h-3 w-3 text-purple-500"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Ie,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),b=()=>{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",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:b,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:R()})}),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:v=>i==null?void 0:i(t.id,{title:v}),isEditable:t.ownership.isOwner&&g,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:k()})]}),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:v=>i==null?void 0:i(t.id,{description:v}),isEditable:t.ownership.isOwner&&g,isPending:l,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:v=>{v.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:y,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:v=>v.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:v=>{v.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),m(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Pa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),u(t)},children:[e.jsx(Se,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),d(t),j(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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 Kt({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function os({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(m=>m.value===t))==null?void 0:d.label)||t,i=a.filter(m=>m.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),n(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function Qt({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(os,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function Wt({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Jt({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(m=>m.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(m=>m.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(Se,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function Xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=M.useRef(null);return M.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ge(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function wr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Zt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function kr(t,n,a){const r=Zt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function Dr({user:t}){return Zt(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 Tr({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=wr((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),m=d?d.newRole:n==null?void 0:n.role,u=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(os,{currentRole:m,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ge(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Er({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(We,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function Ir({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function Ar({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],m=c.orgWide||[],u=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,g)=>{var x,N;const j=((x=n.find(k=>k.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((N=n.find(k=>k.id===f.orgUserId))==null?void 0:N.type)||"",y=ge(f.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),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,g)=>{var x,N;const j=((x=n.find(k=>k.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((N=n.find(k=>k.id===f.tenantUserId))==null?void 0:N.type)||"",y=ge(f.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),u.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:u.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const j=ge(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),!i.length&&!d.length&&!m.length&&!u.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,m)=>{var g,j;const u=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(p=>p.id===d.tenantUserId))==null?void 0:j.type)||"",f=ge(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},m)}),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,m)=>{const u=ge(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},m)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const m=((f=n.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",u=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=ge(i.role,a(u));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:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const m=ge(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Mr({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function Lr({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?u(t.id):h(t.id):u(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(Dr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(os,{currentRole:n==null?void 0:n.role,onRoleChange:j=>f(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(Tr,{user:t,userShare:n,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(os,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Er,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(Ir,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function en({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),p=c||(b=>{const S=u.some(E=>E.id===b),v=h.includes(b);S?j.removeSelectedUser(b):v?j.removeUserFromRemove(b):j.addSelectedUser({id:b,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,x=d||j.addUserToRemove,N=m||((b,S,v)=>{j.addUserToUpdate({id:b,currentRole:S,newRole:v})}),k=l,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 (",(k??[]).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(Ar,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===k.length?j.setSelectedUsers([]):j.setSelectedUsers(k.map(b=>({id:b.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===k.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:n,isSearching:a,searchQuery:g,availableUsers:k||[]}),!n&&!a&&(k==null?void 0:k.length)>0&&k.map(b=>{const S=t?kr(b,t,o):void 0,v=R.includes(b.id),E=!!S,w=E&&!v,O=u.some(T=>T.id===b.id),D=u.find(T=>T.id===b.id),F=r(b.type);return e.jsx(Lr,{user:b,userShare:S,isUserRemoving:v,hasAccess:w,hasAccessFromAPI:E,isSelected:O,selectedUser:D,roleOptions:F,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:N,handleUserRoleChange:y},b.id)})]})]})}function sn({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(Ie,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Me=()=>[{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 Rr({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),m=Me().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),u=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:u,f=n.role!=="NONE"&&!o&&(!l||l.newRole===u),g=l!==null&&l.newRole!==u,j=o,p=u==="NONE"||!u,y=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},x=N=>{r(u,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||p?"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(Se,{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"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(j||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||p?"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:m.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function tn({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const m=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:m(n.role)}:{role:"NONE"},f=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,g=(p,y)=>{o(p,y)},j=()=>{c()};return e.jsx(Rr,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:d})}const Or=async(t,n={})=>{const a={};return n.search&&(a.search=n.search),n.type&&(a.type=n.type),n.active!==void 0&&(a.active=n.active.toString()),n.tenantId&&(a.tenantId=n.tenantId),n.limit&&(a.limit=n.limit.toString()),n.offset&&(a.offset=n.offset.toString()),n.page&&(a.page=n.page.toString()),n.pageSize&&(a.pageSize=n.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,a)};function Fr(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Or((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Ae(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=Z.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:m}=Fr(c),u=jr(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function Br({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var ee,Q;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[N,k]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},b=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:E}=Ae({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:R(),tenantId:b()});M.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,N]);const w=q=>{var $,B;const H=q;if(k(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const _=(B=($=v==null?void 0:v.shares)==null?void 0:$.orgUsersOnly)==null?void 0:B[0];_&&_.role!==void 0&&x.setOrgWideRole(_.role)}},O=S.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),D=S.filter(q=>f.some(H=>H.id===q.id)),F=q=>{var _,Y;const H=f.some(J=>J.id===q),$=g.includes(q),B=(Y=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:Y.some(J=>J.orgUserId===q);H?x.removeSelectedUser(q):$?x.removeUserFromRemove(q):B||x.addSelectedUser({id:q,role:"VIEWER"})},T=(q,H)=>{x.updateSelectedUserRole(q,H)},I=q=>{x.addUserToRemove(q),x.removeSelectedUser(q)},C=q=>{x.removeUserFromRemove(q)},L=q=>{x.removeUserFromUpdate(q)},A=(q,H)=>{x.setOrgWideRole(H)},P=()=>{x.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(Q=(ee=v==null?void 0:v.shares)==null?void 0:ee.orgUsersOnly)==null?void 0:Q[0];M.useEffect(()=>{N==="all_users"&&V&&V.role!==void 0&&x.setOrgWideRole(V.role)},[N,V,x]);const U=E,W=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(sn,{shareType:N,onShareTypeChange:w,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Ie,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Kt,{value:m,onChange:u}),e.jsx(Qt,{selectedUsers:f,selectedUserObjects:D,onRemove:F,onRoleChange:T,getRoleOptions:Me}),e.jsx(Wt,{usersToRemove:g,allUsers:O,onRemove:C}),e.jsx(Jt,{usersToUpdate:j,allUsers:O,onRemove:L,getRoleOptions:Me}),e.jsx(en,{existingShares:v,isInitialLoading:U,isSearching:W,resource:t,onShare:()=>{},getRoleOptions:Me,allUsers:O,currentUser:a,handleUserToggle:F,handleUserRoleChange:T,handleRemoveAccess:I,handleUpdateAccess:(q,H,$)=>{x.addUserToUpdate({id:q,currentRole:H,newRole:$})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(tn,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:A,onRemoveAccess:P,allUsersToUpdate:p==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:p==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function yt({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var _;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:N,isLoading:k}=ur({enabled:(a==null?void 0:a.type)==="organization"}),[R,b]=M.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,a==null?void 0:a.type]);const S=Y=>{var te,re,ne,ue;b(Y);let J;if(Y==="specific_tenant_users"?J="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?J="all_users":J="specific_users",r==null||r(J),(a==null?void 0:a.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&x.setSelectedTenant(a.tenantId))):(x.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&x.setCurrentMode("allTenants")),Y==="all_tenant_users"){const K=(re=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:re[0];K&&K.role!==void 0&&x.setTenantWideRole(K.role)}else if(Y==="all_tenants"){const K=(ue=(ne=w==null?void 0:w.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:ue[0];K&&K.role!==void 0&&x.setAllTenantsRole(K.role)}},v=Y=>{x.setSelectedTenant(Y)},{allUsers:E,existingShares:w,isLoadingUsers:O,isErrorLoadingUsers:D,isLoadingShares:F,isErrorLoadingShares:T}=Ae({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:y}),I=Y=>{var ne,ue;const J=u.some(K=>K.id===Y),te=h.includes(Y),re=(ue=(ne=w==null?void 0:w.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:ue.some(K=>K.tenantUserId===Y);J?x.removeSelectedUser(Y):te?x.removeUserFromRemove(Y):re||x.addSelectedUser({id:Y,role:"VIEWER"})},C=(Y,J)=>{x.updateSelectedUserRole(Y,J)},L=Y=>{x.addUserToRemove(Y),x.removeSelectedUser(Y)},A=Y=>{x.removeUserFromRemove(Y)},P=Y=>{x.removeUserFromUpdate(Y)},V=(Y,J,te)=>{x.addUserToUpdate({id:Y,currentRole:J,newRole:te})},U=(Y,J)=>{R==="all_tenant_users"?x.setTenantWideRole(J):R==="all_tenants"&&x.setAllTenantsRole(J)},W=()=>{R==="all_tenant_users"?x.setTenantWideRole("VIEWER"):R==="all_tenants"&&x.setAllTenantsRole("VIEWER")},Q=(()=>{var Y,J,te,re;return g==="allTenants"?(J=(Y=w==null?void 0:w.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:J[0]:g==="allTenantUsers"?(re=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:re[0]:null})();M.useEffect(()=>{var Y,J,te,re;if(R==="all_tenant_users"){const ne=(J=(Y=w==null?void 0:w.shares)==null?void 0:Y.tenantWide)==null?void 0:J[0];ne&&ne.role!==void 0&&x.setTenantWideRole(ne.role)}else if(R==="all_tenants"){const ne=(re=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:re[0];ne&&ne.role!==void 0&&x.setAllTenantsRole(ne.role)}},[R,w,x]);const q=E.filter(Y=>u.some(J=>J.id===Y.id)),H=O||F,$=D||T,B=()=>(a==null?void 0:a.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[$&&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"})]})}),!$&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(sn,{shareType:R,onShareTypeChange:S,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(Se,{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(Ie,{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(xt,{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(Ie,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.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:y||"",onValueChange:v,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(_=N==null?void 0:N.tenants)==null?void 0:_.map(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),B()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Kt,{value:i,onChange:m}),e.jsx(Qt,{selectedUsers:u,selectedUserObjects:q,onRemove:Y=>I(Y),onRoleChange:C,getRoleOptions:Me}),e.jsx(Wt,{usersToRemove:h,allUsers:E,onRemove:A}),e.jsx(Jt,{usersToUpdate:f,allUsers:E,onRemove:P,getRoleOptions:Me}),e.jsx(en,{existingShares:w,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Me,allUsers:E,currentUser:a,handleUserToggle:I,handleUserRoleChange:C,handleRemoveAccess:L,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(tn,{currentUser:a,currentShare:Q,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:U,onRemoveAccess:W,allUsersToUpdate:g==="allTenantUsers"&&((Q==null?void 0:Q.role)===void 0||j!==Q.role)||g==="allTenants"&&((Q==null?void 0:Q.role)===void 0||p!==Q.role)?{currentRole:(Q==null?void 0:Q.role)||"VIEWER",newRole:g==="allTenantUsers"?j:p}:null,allUsersToRemove:g==="allTenantUsers"&&(Q==null?void 0:Q.role)===void 0||g==="allTenants"&&(Q==null?void 0:Q.role)===void 0})}):null}):(a==null?void 0:a.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(xt,{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 nn=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,n,a,r,l,o,c,i,d]),u=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!o)return!1}else if(n==="specificTenantUsers")return o?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0}return!1},[t,n,a,r,l,o]);return{buildShareData:m,validateShareData:u,isCurrentStateValid:h,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function vt({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:N,isCurrentStateValid:k}=nn(),R=a||r||l,b=()=>{var O,D,F,T;if(R)return"Updating...";if(i==="specific_users"){if(u.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=u.length+h.length+f.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&f.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:f.length>0&&u.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 j===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenants";const C=I.role;return p===C?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(T=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const C=I.role;return y===C?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(u.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=u.length+h.length+f.length;return I===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&u.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&f.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:f.length>0&&u.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"&&!g||i==="specific_tenant_users"&&!g?!0:!k,v=()=>{const O=x();O&&N(O)&&o(O)},E=()=>{var O,D,F,T;if(i==="all_users")if(!d||d.role===void 0){const I=x();I&&N(I)&&o(I)}else{const I=d.role;if(j===I)m==null||m();else{const L=x();if(L&&N(L)){const A={...L,updateAccess:!0};o(A)}}}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0){const C=x();C&&N(C)&&o(C)}else{const C=I.role;if(p===C)m==null||m();else{const A=x();if(A&&N(A)){const P={...A,updateAccess:!0};o(P)}}}}else if(i==="all_tenant_users"){const I=(T=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!I||I.role===void 0){const C=x();C&&N(C)&&o(C)}else{const C=I.role;if(y===C)m==null||m();else{const A=x();if(A&&N(A)){const P={...A,updateAccess:!0};o(P)}}}}},w=()=>{var O,D,F,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return j===I?"destructive":"default"}else if(i==="all_tenants"){const I=(D=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const C=I.role;return p===C?"destructive":"default"}else if(i==="all_tenant_users"){const I=(T=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!I||I.role===void 0)return"default";const C=I.role;return y===C?"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:(u.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:v,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(We,{className:"mr-2 h-4 w-4"}),!R&&b()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:E,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(Se,{className:"mr-2 h-4 w-4"}),!R&&b()]})]})}function Pr({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=nn(),p=n||a||r,y=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const b=d.length+m.length+u.length;return b===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${b} user${b!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.length!==1?"s":""}`:`Update access for ${b} user${b!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const b=i.role;return h===b?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!j,N=()=>{const b=f();b&&g(b)&&l(b)},k=()=>{if(!i||i.role==="NONE"){const b=f();b&&g(b)&&l(b)}else{const b=i.role;if(h===b){const v=f();if(v&&g(v)){const E={...v,removeAccess:!0};l(E)}}else{const v=f();if(v&&g(v)){const E={...v,updateAccess:!0};l(E)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||u.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(We,{className:"mr-2 h-4 w-4"}),!p&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:x(),variant:R(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(We,{className:"mr-2 h-4 w-4"}),!p&&y()]})]})}function an({resource:t,resourceType:n,isSharing:a,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var v,E,w,O;const{currentUser:d}=we(),[m,u]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:y}=Ae({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:x}=Ae({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),N=(E=(v=y==null?void 0:y.shares)==null?void 0:v.tenantWide)==null?void 0:E[0],k=(O=(w=x==null?void 0:x.shares)==null?void 0:w.orgUsersOnly)==null?void 0:O[0],R=()=>{if(j==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},b=M.useCallback(()=>{g.resetShareState(),o()},[g,o]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:b,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(We,{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:j,onValueChange:D=>{const F=D;g.setSelectedTab(F),g.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(Br,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:f,isSharing:a,isUpdating:l,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(yt,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:D=>u(D),isSharing:a,isUpdating:l,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(yt,{resource:t,resourceType:n,currentUser:d,onShareTabTypeChange:D=>u(D),isSharing:a,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?j==="org"?e.jsx(vt,{resource:t,existingShares:x,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:i}):e.jsx(vt,{resource:t,existingShares:y,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:N,onRemoveAccess:i}):e.jsx(Pr,{resource:t,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:N,onRemoveAccess:i})})]})})}function pe(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ee(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function rn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const f=pe(r,l,m.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(u&&u.length>0){const f=Ee(r,l,u.map(g=>{var p,y;const j=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:y.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:f}=t;if(u&&u.length>0){const g=Ee(r,l,u.map(j=>{var y,x;const p=(x=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:x.find(N=>N.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{d()}})}),m&&m.length>0){const g=pe(r,l,m.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=Ee(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=pe(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else{const m=pe(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const f=pe(r,l,m.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(u&&u.length>0){const f=Ee(r,l,u.map(g=>{var p,y;const j=(y=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:y.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function ln(t,n,a,r){var m,u,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Ee(l,o,t.map(y=>{var N,k;const x=(k=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:k.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const p=n==="tenant"&&a==="allTenants",y=n==="tenant"&&a==="allTenantUsers";if(p){const x=(u=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(x){const N=Ee(l,o,[{scope:"all_tenants_only",role:x.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(y){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const N=Ee(l,o,[{scope:"all_tenant_users",role:x.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const x=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(x){const N=Ee(l,o,[{scope:"org_users_only",role:x.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function zr(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=we(),{existingShares:d}=Ae({debouncedSearchQuery:"",resourceId:t||"",resourceType:Z.DASHBOARD,userType:"tenant"}),m=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(f=>{if(!t)return;const g={resourceType:Z.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:m};rn(f,g,i)},[t,n,a,d,m,i]),h=M.useCallback(()=>{if(!t)return;const f={resourceType:Z.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:m};ln(l,o||"",c||"",f)},[t,n,a,d,m,l,o,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Vr(t,n,a){const{currentUser:r}=we(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=Ae({debouncedSearchQuery:"",resourceId:t||"",resourceType:Z.VISUAL,userType:"tenant"}),m=M.useCallback(()=>{l.resetUserSelections()},[l]),u=M.useCallback(f=>{if(!t)return;const g={resourceType:Z.VISUAL,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:m};rn(f,g,r)},[t,n,a,d,m,r]),h=M.useCallback(()=>{if(!t)return;const f={resourceType:Z.VISUAL,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:m};ln(o,c||"",i||"",f)},[t,n,a,d,m,o,c,i]);return{handleShareSubmit:u,handleRemoveAccess:h}}function _r(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ys(t){const[n,a]=M.useState(null),[r,l]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Ur(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function bt(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],l=a.getQueryData(r);if(l)return console.log("Using cached visual data for:",n),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",n);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function $r(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function qr(){var f;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ys(((f=a.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),m=s.useEditorStore(g=>g.isShowingVisual),u=a.sql;return{getUpdatedFrame:M.useCallback(()=>{var x;let g=u;u&&!u.includes("{{")&&(g=_r(u),t(g));const j=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:m?a.customCfg:null,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},y=n.cards.map(N=>N.id===a.id?p:N);return{...n,cards:y,activeCardId:Ur(y,n.activeCardId)}},[a,n,m,l,o,c,i,d,t,r,u])}}function Gs(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=vr((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=M.useCallback(async p=>{try{r(p);const{data:y,fromCache:x}=await bt((t==null?void 0:t.accessToken)||"",p.id,n);return $r(y,l,o,c,i),{success:!0,fromCache:x}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,l,o,c,i]),j=M.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:x}=await bt((t==null?void 0:t.accessToken)||"",p.id,n),N=y.frameObject;if(!N)return{success:!1,error:"Visual has no frame data"};const k={...N,id:s.v4()};return m(h,k,"end"),c(!0),d(k.id),u(!1),{success:!0,fromCache:x}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,m,c,d,u]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:qr().getUpdatedFrame,refetch:f.refetch}}function Yr(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(!1),[u,h]=M.useState(null),[f,g]=M.useState(!1),[j,p]=M.useState(null),[y,x]=M.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:b}=Gs(),{resources:S,isLoading:v,isError:E,createResource:w,updateResource:O,deleteResource:D,duplicateResource:F,shareResource:T,isCreating:I,isDeleting:C,removeResourceShares:L,isSharing:A,isRemovingShares:P,isUpdatingShares:V}=Nr(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:U,handleRemoveAccess:W}=Vr((u==null?void 0:u.id)||null,T,L);we();const ee=S.filter(z=>{var X,le;return((X=z==null?void 0:z.title)==null?void 0:X.toLowerCase().includes(t.toLowerCase()))||((le=z==null?void 0:z.description)==null?void 0:le.toLowerCase().includes(t.toLowerCase()))}),Q=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&w({title:l,description:c,isPrivate:!1})},H=z=>{p(z),g(!0)},$=()=>{j&&D(j.id)},{startUpdating:B,stopUpdating:_,isUpdating:Y}=Ht(),J=(z,X)=>{const le=X.title!==void 0?"title":"description";B(z,le),O({resourceId:z,data:X},{onSuccess:()=>{_(z,le)},onError:()=>{_(z,le)}})},te=z=>{x(z),F(z,{onSettled:()=>x(null)})},re=z=>{R(z)},ne=z=>{b(z)},ue=z=>{const X=S.find(le=>le.id===z);X&&O({resourceId:z,data:{isPrivate:!X.isPrivate}})},K=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Ae({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:Z.VISUAL,userType:"tenant"}),v?e.jsx(Yt,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:z=>o(z.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:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),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:z=>n(z.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:ee.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(xs,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):ee.map(z=>e.jsx(Sr,{visual:z,onAddVisual:ne,onEditVisual:re,onUpdateVisual:J,onDeleteClick:H,onDuplicateVisual:te,onTogglePrivacy:ue,onShareVisual:K,isDeleting:C,isDuplicating:y===z.id,isTitleUpdating:Y(z.id,"title"),isDescriptionUpdating:Y(z.id,"description"),formatDate:Q},z.id))})}),d&&u&&e.jsx(an,{resource:u,resourceType:Z.VISUAL,onShare:U,isSharing:A,isRemoving:P,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:W}),e.jsx(s.AlertDialog,{open:f,onOpenChange:z=>{!z&&C||(g(z),z||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:C,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:C,children:C?"Deleting...":"Delete"})]})]})})]})}function Gr({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:u,onDashboardItemClick:h}){var S;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),[j,p]=M.useState(!1),[y,x]=M.useState(!1),N=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen);M.useEffect(()=>{a?(p(!0),x(!0)):y&&(p(!1),x(!1))},[a,y]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bt,{className:"h-3 w-3 text-purple-500"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Ie,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),b=()=>{f(t),o(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",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:b,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:R()})}),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:v=>c==null?void 0:c(t.id,{title:v}),isEditable:t.permissions.canEdit&&g,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:k()})]}),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:v=>c==null?void 0:c(t.id,{description:v}),isEditable:t.permissions.canEdit&&g,isPending:l,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:j,onOpenChange:p,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:v=>v.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:v=>{v.preventDefault(),v.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),m(t)},children:[e.jsx(Se,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t),N(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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:u(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Hr({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 Kr(t){const[n,a]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[m,u]=M.useState(!1),[h,f]=M.useState(null),[g,j]=M.useState(!1),[p,y]=M.useState(null),[x,N]=M.useState(null),k=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:b,isLoading:S,isError:v,createResource:E,updateResource:w,deleteResource:O,duplicateResource:D,isCreating:F,isDeleting:T,isSharing:I,isRemovingShares:C,isUpdatingShares:L,shareResource:A,removeResourceShares:P}=br(()=>{j(!1),y(null),k&&R(k)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:U}=zr((h==null?void 0:h.id)||null,A,P),{currentUser:W}=we(),ee=b.filter(K=>{var z,X;return((z=K==null?void 0:K.title)==null?void 0:z.toLowerCase().includes(n.toLowerCase()))||((X=K==null?void 0:K.description)==null?void 0:X.toLowerCase().includes(n.toLowerCase()))}),Q=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&E({title:o,description:i,isPrivate:!1})},H=K=>{var z;(z=t.onLoadDashboard)==null||z.call(t,K)},$=K=>{y(K),j(!0)},B=()=>{p&&O(p.id)},_=K=>{N(K),D(K,{onSettled:()=>N(null)})},{startUpdating:Y,stopUpdating:J,isUpdating:te}=Ht(),re=(K,z)=>{const X=z.title!==void 0?"title":"description";Y(K,X),w({resourceId:K,data:z},{onSuccess:()=>{J(K,X)},onError:()=>{J(K,X)}})},ne=K=>{const z=b.find(X=>X.id===K);z&&w({resourceId:K,data:{isPrivate:!z.isPrivate}})},ue=K=>{f(K),W==null||W.type,u(!0)};return Ae({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:Z.DASHBOARD,userType:"tenant"}),S?e.jsx(Yt,{}):v?e.jsx(Hr,{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:o,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:q,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||F,children:F?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:F,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:F,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),F?"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:n,onChange:K=>a(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:ee.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ba,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):ee.map(K=>e.jsx(Gr,{dashboard:K,isDeleting:T,isDuplicating:x===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:H,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:$,onDuplicateDashboard:_,onTogglePrivacy:ne,onShareDashboard:ue,formatDate:Q,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),m&&h&&e.jsx(an,{resource:h,resourceType:Z.DASHBOARD,onShare:V,isSharing:I,isRemoving:C,isUpdating:L,onClose:()=>{u(!1),f(null)},onRemoveAccess:U}),e.jsx(s.AlertDialog,{open:g,onOpenChange:K=>{!K&&T||(j(K),K||y(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 "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:T,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),B()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:T,children:T?"Deleting...":"Delete"})]})]})})]})}function on({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(g=>g.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(g=>g.actions),{currentUser:c}=we(),i=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Xt(n,{enabled:t}),h=g=>{},f=g=>{console.log("Editing dashboard:",g)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",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:n,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:m,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(Kr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Yr,{})})]})})]})})}function Qr(){var H,$;const{authToken:t,tokenProps:n}=s.useSemaphorContext();s.useDashboardStore(B=>B.theme);const a=s.useDashboardStore(B=>B.lenses),r=s.useDashboardStore(B=>B.selectedLensId),l=a==null?void 0:a.find(B=>B.id===r),o=s.useDashboardStore(B=>B.dashboard);s.useDashboardStore(B=>B.selectedSheetId);const c=s.useDashboardStore(B=>B.isDashboardEditing),i=s.useEditorStore(B=>B.card),d=s.useEditorStore(B=>B.selectedConnectionId),[m,u]=M.useState(!1),h=s.useDashboardStore(B=>B.isDashboardPanelOpen),f=s.useDashboardStore(B=>B.actions.setIsDashboardPanelOpen),g=s.useDashboardStore(B=>B.filterValues),j=s.useDashboardStore(B=>B.isVisualEditing),p=s.useManagementStore(B=>B.selectedDashboard),y=s.useManagementStore(B=>B.initialDashboard),x=p?($=p==null?void 0:p.permissions)==null?void 0:$.canEdit:(H=y==null?void 0:y.permissions)==null?void 0:H.canEdit,N=s.useDashboardStore(B=>B.showFilters);s.useDashboardStore(B=>B.showDashboardJSON);const k=s.useDashboardStore(B=>B.onSaveFunction),R=s.useDashboardStore(B=>B.actions.setShowFilters),{addFrame:b,setSelectedFrameId:S}=s.useDashboardStore(B=>B.actions),{getSelectedSheet:v,setIsDashboardEditing:E,setShowDashboardJSON:w}=s.useDashboardStore(B=>B.actions),O=v(),{setInitialDashboard:D}=s.useManagementStore(B=>B.actions),{resources:F}=qs(Z.DASHBOARD);M.useEffect(()=>{if(F&&F.length>0){const B=o==null?void 0:o.id;if(B){const _=F.find(Y=>Y.id===B);_&&D(_)}}},[F,o==null?void 0:o.id,D]);const T=n.orgUserId||n.tenantId,I=c&&!j&&T&&x;function C(){var J,te;const B=i.dataSource;if(B)return B;const _=(te=(J=o.aiContext)==null?void 0:J.selectedEntities)==null?void 0:te[0],Y=_==null?void 0:_.type;if(_)return{connectionId:_.connectionId,connectionType:_.connectionType,type:Y,selectedEntities:[_]}}const L=()=>{if(!c||!O)return;const _={dataSource:C(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},Y={id:s.v4(),cards:[_],activeCardId:_.id};b(O.id,Y),S(Y.id)},A=()=>{E(!0)},[P,V]=M.useState(!1),U=Gt(Z.DASHBOARD);async function W(){const B=ls(o);V(!0);const _={template:B};U.mutate({resourceId:B.id,data:_},{onSuccess:()=>{V(!1),s.ue.success("Dashboard saved!")},onError:()=>{V(!1),s.ue.error("Failed to save dashboard")}})}async function ee(){if(u(!0),!r||!l)return;const B=ls(o),_=JSON.stringify(B),Y={...l,template:_,filterValues:g};await Ms(Y,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),k==null||k(B),u(!1)}if(j)return null;const Q=(l==null?void 0:l.name)||o.title,q=n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[q&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ka,{className:"h-4 w-4"})}),!j&&e.jsx(s.Label,{children:Q})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!j&&e.jsx(er,{}),!j&&e.jsx(qt,{}),c&&!j&&T&&e.jsx(Xa,{}),!j&&T&&e.jsx(Za,{}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:L,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!j&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:A,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{E(!1),w(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!j&&T&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:ee,size:"sm",children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),I&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:P,onClick:W,size:"sm",children:[P?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(As,{className:"mr-2 h-4 w-4"}),P?"Saving...":"Save"]}),!N&&!j&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>R(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!j&&c&&!1,!j&&!1,!j&&e.jsx(on,{isOpen:h,onClose:()=>f(!1)})]})]})}function Wr({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const u=xe.useRef(null),[h,f]=xe.useState(!1),[g,j]=xe.useState("100%"),p=m?[...n||[],{id:"none",name:"None"}]:n;xe.useLayoutEffect(()=>{u.current&&j(u.current.offsetWidth)},[]);function y(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(k=>k.id===a))==null?void 0:N.name:`Select ${t}`}function x(N,k){r(k),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,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:y()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Pt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:k=>x(k,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function qe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":l?"Error":a;function f(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Fa,{className:"size-4"});if(t==="Table")return e.jsx(Ye,{className:"size-4"});if(t==="Model")return e.jsx(ia,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:m,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...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Pt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,y)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Wr,{icon:f(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:u==="select"?g():j()})})}function Jr({column:t}){const[n,a]=M.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:m}=s.useEditorAside(),u=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,y){var R;const x=s.createSqlGenConfig(p,i,y),N=(R=d==null?void 0:d.find(b=>b.id===c))==null?void 0:R.name;u(x);const k=s.getSql(x,s.fmt(l||""),s.fmt(r),N||"",m,o||"");k&&(h(k),f(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function Hs({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(Fe,{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(Je,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ca,{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 ys({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",n),children:[e.jsx(Hs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Xr({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Zr({onClick:t,column:n}){const a=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return i(u)||d(u)||m(u)}function i(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return l==null?void 0:l.some(h=>h.name===u.column_name)}function m(u){return o==null?void 0:o.some(h=>h.name===u.column_name)}return e.jsxs("div",{onClick:()=>t(n),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(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ys,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ys,{column:n})}),e.jsx(Xr,{id:n.column_name,type:"column",children:e.jsx(ys,{column:n})})]})}const vs={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},Ns={id:"__placeholder__",role:"metric",type:"number"},Cs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},cn={id:"__placeholder__"},Le="droppable-group-by",Re="droppable-metrics",Oe="droppable-pivot-by",is="sortable-group-by",Ls="sortable-metrics",cs="sortable-pivot-by",Rs="droppable-filters",Os="sortable-filters",Ks="sortable-order-by";function el(){const t=s.useDndStore(I=>I.insertIndex),n=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.groupByColumns)||[]}),a=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.metricColumns)||[]}),r=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.filterColumns)||[]}),l=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.orderBy)||[]}),o=s.useEditorStore(I=>{var C;return((C=I.card.queryConfig)==null?void 0:C.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:p,setPivotByColumns:y}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var A;const{active:C,over:L}=I;if(((A=C.data.current)==null?void 0:A.type)==="column"&&L){const P=L.id,V=x.find(Q=>Q.column_name===C.id);if(!V)return;const U=s.isNumberDataType(V.data_type),W=s.isTextDataType(V.data_type),ee=s.isDateDataType(V.data_type);if(W||ee){if(n.some(q=>q.id===P)){const q=n.findIndex($=>$.id===P);c(q);const H=n.filter($=>$.id!==vs.id);H.splice(q,0,vs),d(H)}else if(L.id===Le){c(n.length);const q=[...n,vs];d(q),m(a),u(r)}}if(W||ee){if(o.some(q=>q.id===P)){const q=o.findIndex($=>$.id===P);c(q);const H=o.filter($=>$.id!==bs.id);H.splice(q,0,bs),h(H)}else if(L.id===Oe){c(o.length);const q=[...o,bs];h(q),d(n),m(a),u(r)}}if(U||W){if(a.some(q=>q.id===P)){console.log("isOverMetricSortable",P);const q=a.findIndex($=>$.id===P);c(q);const H=a.filter($=>$.id!==Ns.id);H.splice(q,0,Ns),m(H)}else if(L.id===Re){c(a.length);const q=[...a,Ns];m(q),u(r),d(n),h(o)}}if(S(V)){if(r.some(q=>q.id===P)){const q=r.findIndex($=>$.id===P);c(q);const H=r.filter($=>$.id!==Cs.id);H.splice(q,0,Cs),u(H)}else if(L.id===Rs){c(r.length);const q=[...r,Cs];u(q),m(a),d(n),h(o)}}}else d(n),m(a),u(r),h(o)};function b(I){i(I.active.id),c(null),d(n),m(a),u(r),h(o)}function S(I){return!r.some(C=>C.name===I.column_name)}function v(I,C="SUM"){const{column_name:L,data_type:A}=I,P=[...a],V=t!==null?t:a.length,U={...I,id:je(L),name:L,label:Xe(L,C),type:A,role:"metric",aggregate:C};P.splice(V,0,U),g(P)}function E(I){const C=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const L=[...o],A=t!==null?t:o.length;let P;C?P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ge(I.column_name,"month"),granularity:"month"},L.splice(A,0,P),y(L)}function w(I){const C=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const L=[...n],A=t!==null?t:n.length;let P;C?P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ge(I.column_name,"month"),granularity:"month"},L.splice(A,0,P),f(L)}function O(I){const C=[...r],L=t!==null?t:r.length,A={...I,id:je(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,N,s.fmt(I.column_name)),role:"filter"};C.splice(L,0,A),j(C)}function D(I){var P,V,U,W,ee,Q,q,H;const{active:C,over:L}=I,A=C.data.current;if((A==null?void 0:A.type)==="column"&&L){const $=x.find(J=>J.column_name===C.id);if(!$)return;const B=s.isNumberDataType($.data_type),_=s.isTextDataType($.data_type),Y=s.isDateDataType($.data_type);(_||Y)&&(L.id===Le||((P=L.data.current)==null?void 0:P.type)===is)&&w($),(_||Y)&&(L.id===Oe||((V=L.data.current)==null?void 0:V.type)===cs)?E($):(B||_)&&(L.id===Re||((U=L.data.current)==null?void 0:U.type)===Ls)?(B&&v($),_&&v($,"COUNT")):S($)&&(L.id===Rs||((W=L.data.current)==null?void 0:W.type)===Os)&&O($)}if(L&&((ee=L.data.current)==null?void 0:ee.type)===is&&n.some($=>$.id===C.id)){const $=n.findIndex(_=>_.id===C.id),B=n.findIndex(_=>_.id===L.id);if($!==-1&&B!==-1&&$!==B){const _=[...n],[Y]=_.splice($,1);_.splice(B,0,Y),f(_)}}if(L&&((Q=L.data.current)==null?void 0:Q.type)===cs&&o.some($=>$.id===C.id)){const $=o.findIndex(_=>_.id===C.id),B=o.findIndex(_=>_.id===L.id);if($!==-1&&B!==-1&&$!==B){const _=[...o],[Y]=_.splice($,1);_.splice(B,0,Y),y(_)}}if(L&&((q=L.data.current)==null?void 0:q.type)===Ls&&a.some($=>$.id===C.id)){const $=a.findIndex(_=>_.id===C.id),B=a.findIndex(_=>_.id===L.id);if($!==-1&&B!==-1&&$!==B){const _=[...a],[Y]=_.splice($,1);_.splice(B,0,Y),g(_)}}if(L&&((H=L.data.current)==null?void 0:H.type)===Os&&r.some($=>$.id===C.id)){const $=r.findIndex(_=>_.id===C.id),B=r.findIndex(_=>_.id===L.id);if($!==-1&&B!==-1&&$!==B){const _=[...r],[Y]=_.splice($,1);_.splice(B,0,Y),j(_)}}F(I),i(null),c(null),d(n),m(a),u(r),h(o)}function F(I){const{active:C,over:L}=I,A=C.data.current;if((A==null?void 0:A.type)===Ks&&L){const P=l.findIndex(U=>Ke(U.columnId)===C.id),V=l.findIndex(U=>Ke(U.columnId)===L.id);if(P!==-1&&V!==-1&&P!==V){const U=[...l],[W]=U.splice(P,1);U.splice(V,0,W),p(U)}}}function T(){i(null),c(null),d(n),m(a),u(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:b,handleDragCancel:T,sensors:k}}function je(t){return`${t}-${s.v4()}`}function Xe(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ke(t){return`${Ks}-${t}`}function Ge(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function sl({schemaName:t,tableName:n,columns:a,status:r}){const l=s.useEditorStore(C=>C.sqlGen),o=s.useEditorStore(C=>C.isDevMode),c=s.useEditorStore(C=>C.selectedConnectionId),i=s.useEditorStore(C=>{var L,A;return(A=(L=C.card)==null?void 0:L.queryConfig)==null?void 0:A.metricColumns});s.useEditorStore(C=>{var L,A;return(A=(L=C.card)==null?void 0:L.queryConfig)==null?void 0:A.groupByColumns});const d=s.useEditorStore(C=>C.selectedDatabaseName),m=s.useEditorStore(C=>C.selectedSchemaName),u=s.useEditorStore(C=>C.selectedTableName),h=s.useEditorStore(C=>C.selectedDatamodelId),f=s.useDashboardStore(C=>C.dashboard.aiScopeTables),{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:y,setCardSql:x,setRunSql:N,setSqlGen:k,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:b,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function E(C){var L;if(o){const A=s.createSqlGenConfig(C,l);k(A);const P=(L=S==null?void 0:S.find(U=>U.id===h))==null?void 0:L.name,V=s.getSql(A,s.fmt(t),s.fmt(n),P||"",b,d||"");V&&(x(V),N(!0))}if(!o){if(s.isTextDataType(C.data_type))if(i&&i.length>0){const A={...C,role:"groupby",id:je(C.column_name),name:C.column_name,type:C.data_type};y(A)}else{const A={...C,role:"metric",id:je(C.column_name),name:C.column_name,label:Xe(C.column_name,"COUNT"),type:C.data_type,aggregate:"COUNT"};p(A)}if(s.isDateDataType(C.data_type)){const A={...C,role:"groupby",id:je(C.column_name),name:C.column_name,type:C.data_type,label:Ge(C.column_name,"month"),granularity:"month"};y(A)}if(s.isNumberDataType(C.data_type)){const A={...C,role:"metric",id:je(C.column_name),name:C.column_name,label:Xe(C.column_name,"SUM"),type:C.data_type,aggregate:"SUM"};p(A)}}}function w(C){C===!0&&(u||v)&&c?(g({connectionId:c,connectionType:b==="S3"||b==="API"?"DuckDb":b||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:b||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function O(){const C=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:b,databaseName:d||""});R(!1);const L=b==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;x(L),N(!0)}function D(){const C=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:b,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${C}`),N(!0)}function F(){return(f==null?void 0:f.find(C=>C.connectionId===c&&(C.tableName===u||C.datamodelName===v)))!==void 0}function T(C){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>E(C),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hs,{column:C}),e.jsx("span",{children:C.column_name})]}),e.jsx("div",{onClick:L=>L.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(C.data_type)&&e.jsx(Jr,{column:C})})]}):e.jsx(Zr,{onClick:E,column:C})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${F()?"Remove from":"Add to"} Assistant Scope`,pressed:F(),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":F(),"text-muted-foreground":!F()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,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(Ma,{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(zt,{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((C,L)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},L))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[o&&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:a==null?void 0:a.map(C=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:T(C)},C.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function dn({ColumnsComponent:t,type:n}){var ve;const a=s.useEditorStore(se=>se.card),r=s.useEditorStore(se=>se.selectedConnectionId),l=s.useDashboardStore(se=>se.showFilters),o=s.useEditorStore(se=>se.selectedDatamodelId),c=s.useEditorStore(se=>se.selectedDatabaseName),i=s.useEditorStore(se=>se.selectedSchemaName),d=s.useEditorStore(se=>se.selectedTableName),m=s.useEditorStore(se=>se.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:g,modelItems:j,schemaItems:p,databaseItems:y,tableItems:x,columns:N,isConnectionsLoading:k,isModelsLoading:R,isConnectionsError:b,isModelsError:S,isDatabasesLoadingOrFetching:v,isDatabaseError:E,isSchemaLoadingOrFetching:w,isSchemaError:O,isColumnsError:D,isColumnsLoadingOrFetching:F,isTableLoadingOrFetching:T,isTableError:I,connectionType:C,isNonDbConnection:L,refetchDatabases:A,refetchModels:P,refetchSchemas:V,refetchTables:U,refetchColumns:W,refetchConnections:ee,handleConnectionChange:Q,handleDatabaseChange:q,handleSchemaChange:H,handleDatamodelChange:$,handleTableChange:B,tableName:_,schemaName:Y}=s.useEditorAside(),{data:J,refetch:te}=s.useDashboardCardQuery(a);function re(){return t?t(Y,_,N):e.jsx(sl,{schemaName:Y,tableName:_,columns:N,status:F?"Loading...":D?"Error":"Success"})}function ne(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ue(se){se===!0?J&&(f(J.userSql),setTimeout(()=>{te()},100)):f(""),h(se)}function K(){if(!r||C==="S3"||C==="API")return null;if(!o||o==="none")return e.jsx(qe,{refetch:A,showNone:!0,onChange:q,isError:E,isLoading:v,items:y,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!L&&(!c||c==="none")&&(!o||o==="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 X(){if(!r||C==="S3"||C==="API")return null;if(!c||c==="none")return e.jsx(qe,{refetch:P,showNone:!0,onChange:$,isError:S,isLoading:R,items:j,value:o||"",title:"Model",type:"combobox"})}function le(){return!r||C==="S3"||C==="API"||!c||c==="none"?null:e.jsx(qe,{refetch:V,onChange:H,isError:O,isLoading:w,items:p,value:i||"",title:"Schema",type:"combobox"})}function ye(){function se(){let ce=!1;return C==="API"?(ce=!1,ce):((C==="S3"||r&&c&&c!=="none"&&i)&&(ce=!0),ce)}return se()?e.jsx(qe,{refetch:U,onChange:B,isError:I,items:x,isLoading:T,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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(qe,{refetch:ee,items:g,title:"Connection",value:r||"",onChange:Q,isLoading:k,isError:b,type:"combobox",connectionTooltip:((ve=g==null?void 0:g.find(se=>se.id===r))==null?void 0:ve.type)||""}),K(),z(),X(),le(),ye()]}),re(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:ue,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ne,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ra,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function un({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function m(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function u(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:m,onMouseUp:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function mn({sql:t,error:n,onDebugWithAssistant:a}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:o,setRunSql:c}=s.useEditorActions();function i(){l(!r),o(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:[n&&e.jsx(un,{error:n}),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(ga,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&a&&e.jsxs(s.Button,{onClick:a,size:"sm",variant:"secondary",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function hn({sql:t,error:n,onDebugWithAssistant:a}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Ot,{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(mn,{sql:t,error:n,onDebugWithAssistant:a})})]})}var xn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Nt=M.createContext&&M.createContext(xn),tl=["attr","size","title"];function nl(t,n){if(t==null)return{};var a=al(t,n),r,l;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(l=0;l<o.length;l++)r=o[l],!(n.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(a[r]=t[r])}return a}function al(t,n){if(t==null)return{};var a={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(n.indexOf(r)>=0)continue;a[r]=t[r]}return a}function ds(){return ds=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},ds.apply(this,arguments)}function Ct(t,n){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);n&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),a.push.apply(a,r)}return a}function us(t){for(var n=1;n<arguments.length;n++){var a=arguments[n]!=null?arguments[n]:{};n%2?Ct(Object(a),!0).forEach(function(r){rl(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Ct(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function rl(t,n,a){return n=ll(n),n in t?Object.defineProperty(t,n,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[n]=a,t}function ll(t){var n=ol(t,"string");return typeof n=="symbol"?n:n+""}function ol(t,n){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,n);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(t)}function pn(t){return t&&t.map((n,a)=>M.createElement(n.tag,us({key:a},n.attr),pn(n.child)))}function ze(t){return n=>M.createElement(il,ds({attr:us({},t.attr)},n),pn(t.child))}function il(t){var n=a=>{var{attr:r,size:l,title:o}=t,c=nl(t,tl),i=l||a.size||"1em",d;return a.className&&(d=a.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ds({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,r,c,{className:d,style:us(us({color:t.color||a.color},a.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),o&&M.createElement("title",null,o),t.children)};return Nt!==void 0?M.createElement(Nt.Consumer,null,a=>n(a)):n(xn)}function cl(t){return ze({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 fn(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:m}=s.useEditorActions(),u=M.useRef(),h=M.useRef({}),f=r.cards.find(p=>p.id===o),g=M.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(u.current&&c){const p=u.current.getModel();p&&(h.current[l.id]=p);let y=h.current[o];if(!y){const x=g();y=c.editor.createModel(x,t),h.current[o]=y}u.current.setModel(y)}d(o,l),m(!0)}},[o,l,d,c,m,t,g]),M.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?p:a;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),M.useEffect(()=>{const p=u.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(p,y){if(u.current=p,!h.current[l.id]){const x=p.getModel(),N=g();h.current[l.id]=x||(y==null?void 0:y.editor.createModel(N,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function dl(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=fn("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ul(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=fn("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function ml({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 Qs({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ys(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Gs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function hl(){const t=s.useQueryClient(),[n,a]=M.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Gs(),c=s.useSelectedVisual(),i=Cr(),d=()=>{const m=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:m}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ws(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:m}=r;d&&m&&a.setQueryData(d,m)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ps(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:m,setCardPreferences:u,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function p(){const y=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),m(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function xl(){const t=s.useQueryClient(),[n,a]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(U=>U.frame);const o=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.isShowingVisual),s.useEditorStore(U=>U.selectedConnectionId),s.useEditorStore(U=>U.tempQueryData),s.useEditorStore(U=>U.selectedDatabaseName),s.useEditorStore(U=>U.selectedDatamodelId),s.useEditorStore(U=>U.selectedSchemaName);const c=s.useEditorStore(U=>U.showAIDialog);s.useEditorStore(U=>U.selectedTableName);const i=s.useEditorStore(U=>{var W;return(W=U==null?void 0:U.card)==null?void 0:W.sql}),d=s.useEditorStore(U=>{var W;return(W=U==null?void 0:U.card)==null?void 0:W.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:p,setCardType:y,setCardPython:x,runAssistant:N,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(U=>U.onSave),s.useEditorStore(U=>U.onClose),s.useEditorStore(U=>U.actions.setSqlGen);const R=s.useEditorStore(U=>U.runSql),b=s.useEditorStore(U=>U.actions.setRunSql),S=s.useEditorStore(U=>U.actions.setIsSqlRunning),{data:v,isLoading:E,isFetching:w,isSuccess:O,isError:D,error:F,queryKey:T,refetch:I,errorMessage:C}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:U}=s.getKeys(v.records);h(U)}},[v,h,j]),M.useEffect(()=>{(E||w)&&S(!0),(D||O)&&S(!1),D&&(h([]),j(""))},[E,w,v,j,D,O,S,h,F]),M.useEffect(()=>{R&&(t.getQueryData(T)||I(),b(!1))},[R,I,b,T,t]);async function L(){const U=`Can you help me debug this query in the current table scope?
407
407
 
408
408
  Error:
409
409
 
@@ -415,12 +415,12 @@
415
415
 
416
416
  ${d?`Python:
417
417
  ${d}`:""}
418
- `;b(U)}function A(){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(ml,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(dl,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(ul,{})}),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||T,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||T?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(hn,{sql:v==null?void 0:v.sql,error:C,onDebugWithAssistant:L}),e.jsx(ps,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:U=>a(U),className:"",size:"sm",children:e.jsx(cl,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{w(!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(Ws,{}),e.jsx(Qs,{})]})]})}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:[P(),A()]}),V()]})}function pl({data:t}){var c;const[n,a]=M.useState([]),l=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const m=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,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),o=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:a,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:n}});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:o.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=o.getRowModel().rows)!=null&&c.length?o.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:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function fl({card:t}){var b,w,R,N,S,v,k,T,O,D,B;const[n,a]=M.useState(!1),[r,l]=M.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(E=>E.themeStyle),d={colors:((w=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:w.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:m}=s.useCustomVisual(((N=t.customCardPreferences)==null?void 0:N.url)||""),u=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(E=>E.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=M.useCallback((E,I)=>{l(C=>({...C,[E]:I}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const p=m((k=t.customCardPreferences)==null?void 0:k.componentName);function y(E){a(E)}const x=Object.keys(((T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)||{}).map(E=>{var L,A,P;const I=(A=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:A[E].cardId,C=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===I);return C||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:[p&&u==="single"&&e.jsx(p,{editing:!0,params:c,theme:d,settings:(O=t.customCardPreferences)==null?void 0:O.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),p&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((D=t.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(E=>{var L,A,P;const I=(A=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:A[E].cardId,C=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===I);if(C)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:E,card:C},C.id+E)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:d,onDataChange:j,settings:x.map(E=>{var I;return(I=E==null?void 0:E.customCardPreferences)==null?void 0:I.settings}),data:x.map(E=>E!=null&&E.id?r==null?void 0:r[E.id]:[])})})]})]},(B=t.customCardPreferences)==null?void 0:B.componentName)})}function gn({className:t,...n}){var k;const a=s.useEditorStore(T=>T.card),r=s.isExplorerCard(a),l=((k=a.customCardPreferences)==null?void 0:k.showCardHeader)??!0,o=s.useEditorStore(T=>T.frame),c=s.useDashboardStore(T=>T.dashboard.filters),i=s.useEditorStore(T=>T.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(T=>T.id===o.filterId),{data:u,isLoading:h,isFetching:f,errorMessage:g,pagination:j,refetch:p}=s.useDashboardCardQuery(a),{setCard:y,updateCardInFrame:x}=s.useEditorActions(),{data:b}=s.useTopoJson(a),w=M.useMemo(()=>a.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:a,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[a,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),R=(T,O)=>{var B,E;const D={...a,paginationConfig:{page:T+1,pageSize:O}};y(D),x(D),a.sql&&((E=(B=a.preferences)==null?void 0:B.tablePrefs)!=null&&E.enableDevModePagination)&&i(!0)},N=M.useMemo(()=>!a.id||!(u!=null&&u.records)?null:s.createChartConfig({card:a,data:u==null?void 0:u.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:b}),[a.id,u==null?void 0:u.records,a.type,a.queryConfig,a.customCfg,a.preferences,b]);function S(T){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(fl,{card:T})})}function v(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return S(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&N)return e.jsx(e.Fragment,{children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(u==null?void 0:u.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||f})});if(a.type==="pivotTable"&&w)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.PivotTableVisual,{card:a,data:w.data,options:w.options,onAggregationChange:T=>{const O=s.handleAggregationChange(T,a.config),D={...a,config:O};y(D),x(D)},onAggregationLabelChange:T=>{const O=s.handleAggregationLabelChange(T,a.config),D={...a,config:O};y(D),x(D)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(u==null?void 0:u.records)||[],groupByColumns:u==null?void 0:u.groupByColumns,pivotSchema:u==null?void 0:u.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:T=>{const O=s.handleAggregationChange(T,a.config),D={...a,config:O};y(D),x(D)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:a.title,onSave:T=>y({...a,title:T}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:a.title||"Add title"})})},a.title),e.jsx(s.Editable,{enabled:!0,text:a.description||"",onSave:T=>y({...a,description:T}),children:e.jsx(s.CardDescription,{children:a.description||"Add description"})},a.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:T=>d({...m,title:T}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const Ss=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),gl=()=>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."})]})]}),jl=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{language:"javascript",value:t,onChange:l})})]}),yl=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function vl(){const[t,n]=M.useState(!1),[a,r]=M.useState(""),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(""),u=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(u),{data:j}=s.useTopoJson(u),{setCardCustomCfg:p,setCustomVisualCode:y}=s.useEditorActions(),x=N=>{var S,v;return JSON.stringify({...N,data:{...N.data,datasets:(v=(S=N.data)==null?void 0:S.datasets)==null?void 0:v.map(k=>({...k,data:[]}))}},null,2)},b=()=>{var S,v;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const N=s.createChartConfig({card:u,data:g.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:j});if(N){r(x(N)),i(((v=u.preferences)==null?void 0:v.customVisualCode)||"");const k=s.merge(N,h);o(x(k))}},w=()=>{try{if(c&&y(c),l){const N=JSON.parse(l),S=s.getObjectDiff(JSON.parse(a),N);p(S),m("")}}catch{m("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick: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(gl,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(gn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(jl,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(yl,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:w,onClose:()=>n(!1)})]})]})}function fs(t){const[n,a]=M.useState(null);return n}function jn(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:n,isLoading:a,isFetching:r,isError:l}}function yn(){const{data:t,isLoading:n,isError:a}=jn(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var m;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((m=t==null?void 0:t.plugins)!=null&&m[d])){const u=t.plugins[d],h=i.data.visuals.map(f=>({name:f.name,pluginName:u.label,componentType:f.componentType,pluginType:u.type,icon:f.icon,chartType:f.chartType,url:u.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function bl({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=yn(),d=M.useCallback((m,u)=>{n(null),a({}),r(m),u&&l({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((m,u)=>e.jsx(Nl,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},`${m.url}-${m.name}-${u}`))})]})}const Nl=({text:t,icon:n,onClick:a})=>{const r=fs(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Js(t){return ze({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 Cl(t){return ze({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 Xs(t){return ze({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 Zs(t){return ze({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 et(t){return ze({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 st(t){return ze({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 vn({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(u,h){o(null),r({}),a(u),["custom","text","map"].includes(u)&&(l(!0),i(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Ye,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Fs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(et,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(zs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Xs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Vs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Us,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Js,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx($s,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ps,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(st,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Lt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(_s,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Qe,{className:s.cn("size-5",n)})})]})}function Sl({chartType:t,className:n,customIcon:a,componentName:r}){const l=fs();switch(t){case"bar":return e.jsx(ms,{className:n});case"line":return e.jsx(hs,{className:n});case"pie":return e.jsx(xs,{className:n});case"radar":return e.jsx(Us,{className:n});case"scatter":return e.jsx(zs,{className:n});case"bubble":return e.jsx(Xs,{className:n});case"doughnut":return e.jsx(Vs,{className:n});case"stackedBar":return e.jsx(Fs,{className:n});case"stackedLine":return e.jsx(et,{className:n});case"polarArea":return e.jsx(Js,{className:n});case"funnel":return e.jsx(Zs,{className:n});case"tornado":case"pyramid":return e.jsx($s,{className:n});case"range":return e.jsx(Ps,{className:n});case"kpi":return e.jsx(st,{className:n});case"text":return e.jsx(Fe,{className:n});case"map":return e.jsx(_s,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Qe,{className:n});default:return e.jsx(Ye,{className:n})}}function bn({variant:t="ghost"}){var o,c;const[n,a]=M.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Sl,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(vn,{onChartTypeChange:()=>a(!1)}),e.jsx(bl,{onChartTypeChange:()=>a(!1)})]})]})}function wl(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(ft,{className:"size-4"}):e.jsx(pt,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(ft,{className:"size-4"}):e.jsx(pt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function Nn(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(wl,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(Sa,{className:"size-4"}),r==="x"&&e.jsx(ma,{className:"size-4"}),r==="y"&&e.jsx(Va,{className:"size-4"}),r==="none"&&e.jsx(Ya,{className:"size-4"})]})]}):null}function kl(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,p)=>{j.dataTransfer.setData("tabIndex",p.toString())},i=j=>{j.preventDefault()},d=(j,p)=>{const y=j.dataTransfer.getData("tabIndex");if(y===p.toString())return;const x=Array.from(t.cards),[b]=x.splice(parseInt(y),1);x.splice(p,0,b),a({...t,cards:x})};function m(j){const p=t.cards.filter(b=>b.id!==j),y=p[0],x={...t,cards:p,activeCardId:y.id};a(x),r(y.id),l(y)}function u(j,p){const y={...t,cards:[...t.cards,p],activeCardId:j.id};a(y),r(p.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};u(n,j)}function f(j){const p={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};u(j,p)}function g(j,p){return j.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||j.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:y}),o({...p,displayTab:y})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(fa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,p),onDragOver:i,onDrop:y=>d(y,p),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...n,tabTitle:y}),o({...n,tabTitle:y})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(xa,{className:"h-4 w-4"})})]})})}function Cn(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:u,isFetching:h}=s.useDashboardCardQuery(n);function f(p){const y=t.cards.find(x=>x.id===p);if(y!=null&&y.sql){r||i(!0),o(p);return}if(y!=null&&y.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const y={...t,cards:t.cards.map(b=>b.id===n.id?n:b),activeCardId:p};l(y);const x=y.cards.find(b=>b.id===p);x.sql&&d(!0),c(x)}function j(){return n.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:m==null?void 0:m.records,isPending:u||h})})}):n.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(gn,{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(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:j()},p.id)),e.jsx(kl,{})]})}function es({children:t}){var R,N;s.useEditorStore(S=>S.frame);const n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:j,errorMessage:p,refetch:y}=s.useDashboardCardQuery(n);function x(){const S=JSON.stringify(f==null?void 0:f.records,null,2),v=new Blob([S],{type:"application/json"}),k=URL.createObjectURL(v),T=document.createElement("a");T.href=k,T.download=`${n.title}.json`,T.click()}function b(){const v=[Object.keys(f==null?void 0:f.records.reduce((D,B)=>({...D,...B}),{})).join(","),...((f==null?void 0:f.records)||[]).map(D=>Object.values(D).join(","))].join(`
419
- `),k=new Blob([v],{type:"text/csv"}),T=URL.createObjectURL(k),O=document.createElement("a");O.href=T,O.download=`${n.title}.csv`,O.click()}function w(){const S=`Can you get the documentation for ${n.type} chart?`;m(S)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(bn,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:w,children:e.jsx(oa,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(vl,{})]}),!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:b,children:e.jsx(Cl,{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(ja,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.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(Nn,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(R=n.preferences)==null?void 0:R.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:S=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:S}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Tl,{})]}),r?e.jsx(Cn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(Dl,{})}),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:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(pl,{data:(f==null?void 0:f.records)||[]}),p&&e.jsx(un,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Dl(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col 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:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Tl(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function El(){var p,y;const t=s.useEditorStore(x=>x.card.customCardPreferences),{data:n}=jn(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),m=(p=d==null?void 0:d.visuals)==null?void 0:p.find(x=>x.name===(t==null?void 0:t.componentName));function u(x,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[x]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function h(x){var w,R;const b=(w=l==null?void 0:l.cards)==null?void 0:w.filter(N=>{var S;return((S=N==null?void 0:N.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(R=x==null?void 0:x.dataInputs)==null?void 0:R.map((N,S)=>{var v,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(fe,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((k=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[S])==null?void 0:k.cardId)||"",onValueChange:T=>u(S,T)})]},S+Math.random())})})}function f(x,b,w=[],R=""){var N,S;return t?x==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[b])||R,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:v.target.value}})}},b):x==="select"?e.jsx(fe,{className:"h-8 w-full",label:"",options:w,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:v}})}}):null:null}function g(x){const b=Object.entries((x==null?void 0:x.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([w,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,w,R.options,R.defaultValue)]},w))})}function j(x){t&&c({...t,visualType:x,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(fe,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:x=>c({...t||{url:"",componentName:""},url:x})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(fe,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(x=>x.type===o).map(x=>({value:x.name,label:x.name})))||[],value:t.componentName,onValueChange:x=>{console.log("changing value",x),c({...t,componentName:x})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(m)})})]})]})]})}function Ve(){const[t,n]=M.useState([]),a=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),o=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),M.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(m,u){var h,f;u?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:m,expression:""}]}):l({...a,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...a,onClickFilter:(f=a==null?void 0:a.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==m)}),n(g=>{const j=[...g];return j[m]=!1,j}))}function i(m,u){var f;const h=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===m?{...g,expression:u.target.value}:g);l({...a,onClickFilter:h})}function d(m){var u,h,f,g;if(t!=null&&t[m]||(h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(j=>j.columnIndex===m))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(j=>j.columnIndex===m))==null?void 0:g.expression,onChange:j=>i(m,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),o==null?void 0:o.map((m,u)=>{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=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===u)),onCheckedChange:g=>c(u,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[u]=!g[u],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function Il({idx:t}){var i;const n=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),a=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:m,datalabels:u}]});else{const h={...o};h.datalabels=u;const f=a==null?void 0:a.map(g=>g.idx===m?h:g);r({...n,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Vt,{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(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ia,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ea,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Al(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function gs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Sn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Al();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:wn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,m)=>e.jsx(kn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function wn(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function kn({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,f;return(f=(h=u.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(u=>u.idx===n),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...i};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(gs,{className:"max-w-[100px]",title:t,children:wn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ms,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(hs,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Rt,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Il,{idx:n})]})]})}function tt(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:u,connectionType:h}=s.useEditorAside();function f(g,j="dashboard"){var v;const p=s.fmt(g.column_name),y=s.fmt(a||""),x=s.fmt(r||""),b=s.fmt(u);let w=s.getQualifiedTableName({schemaName:x,tableName:b,connectionType:h,databaseName:y}),R=`${w}.${p}`;const N=(v=m==null?void 0:m.find(k=>k.id===n))==null?void 0:v.name;n&&n!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${N}.${p}`,w=`${s.DATAMODEL_NAMESPCACE}.${N}`);const S=o==null?void 0:o.find(k=>k.column===R&&k.table===b&&(k.database===y||k.database===a));if(S)d(S.id),i(S.id);else{const k=s.v4();return u==="api"&&t?(c({location:j,id:k,column:R,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,w,p)}),k):(c({id:k,location:j,column:R,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,w,p)}),k)}}return{assignFilter:f}}function He(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=tt();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Ml,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Ml({columns:t,onSelect:n}){var c;const[a,r]=xe.useState(!1),[l,o]=xe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const m=d===l?"":d;o(m),r(!1),m&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Ll({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Sn,{})})]}),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(Ve,{}),e.jsx(He,{})]})]})]})})}function Rl({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ve,{}),e.jsx(He,{})]})]})]})})}function Dn(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var u;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(u=a==null?void 0:a.chartOptions)==null?void 0:u.plugins,...d}}};r(m)}function o(){var i,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Ol={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Bl={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Fl(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Pl(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Dn,{}),e.jsx(Ve,{}),e.jsx(He,{})]})]})}function Pl(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(Ol,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(Bl,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 zl(){var u,h,f,g,j;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.decimalPlaces});const o=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.locale}),c=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),m=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((u=t==null?void 0:t.formatNumber)!=null&&u.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var y,x,b;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",p,((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var y,x,b;console.log("currency",p),l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,p==="none"?"":p,((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),m.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var y,x,b;return l(Number(p),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var y,x,b;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(s.ColorFormat,{colorRanges:i,setColorRanges:d})]})]})}function Vl(){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(zl,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ws({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const _l=[{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"}],Ul=["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"],$l=Ul.map(t=>({label:t,value:t}));function ql(){var d,m,u,h,f,g,j,p,y,x,b,w,R,N,S,v,k,T;const t=s.useEditorStore(O=>O.card),n=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[a,r]=M.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(ws,{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(ws,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(fe,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),l({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(fe,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(fe,{className:"h-9",options:_l,value:((p=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(fe,{className:"h-9",options:$l,value:((x=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:x.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ws,{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:((w=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:w.projectionScale)||1,onChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(N=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:S[0])||0,onChange:O=>{var D,B,E,I;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[Number(O.target.value),((I=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.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:((T=(k=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:T[1])||0,onChange:O=>{var D,B,E,I;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[((I=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:I[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ve,{})]})}function Yl(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ss({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Yl,{})})]}),!["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(Ve,{}),e.jsx(He,{})]})]})]})})}function Gl(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(fe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Sn,{})]})]}),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(Ve,{}),e.jsx(He,{})]})]})]})})}function Hl({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ve,{}),e.jsx(He,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Tn({color:t,onColorChange:n,onClose:a}){const[r,l]=M.useState(0),[o,c]=M.useState(100),[i,d]=M.useState(50),[m,u]=M.useState(t);M.useEffect(()=>{const y=St(t);if(y){const x=wt(y.r,y.g,y.b);l(x.h),c(x.s),d(x.l),u(t)}},[t]);const h=y=>{l(y),g(y,o,i)},f=y=>{const x=y.currentTarget.getBoundingClientRect(),b=Math.max(0,Math.min(1,(y.clientX-x.left)/x.width)),w=Math.max(0,Math.min(1,(y.clientY-x.top)/x.height)),R=b*100,N=(1-w)*100;c(R),d(N),g(r,R,N)},g=(y,x,b)=>{const w=Ql(y,x,b),R=Kl(w.r,w.g,w.b);u(R)},j=y=>{if(u(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const x=St(y);if(x){const b=wt(x.r,x.g,x.b);l(b.h),c(b.s),d(b.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(n(m),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:y=>{y.buttons===1&&f(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:m,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function St(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Kl(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function wt(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Ql(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(m,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(u-m)*6*h:h<.5?u:h<.6666666666666666?m+(u-m)*(.6666666666666666-h)*6:m),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Wl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function En(){var w,R,N,S,v,k,T,O,D,B;const t=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>{var I;return(I=E.card)==null?void 0:I.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=M.useState({}),[i,d]=M.useState(null),[m,u]=M.useState(null),h=M.useMemo(()=>{var L,A,P,V,U,W,ee;if(!(l!=null&&l.records)||l.records.length===0)return[];const E=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",I=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",C=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((E||I)&&C){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const Q=new Set;return l.pivotSchema.forEach(q=>{q.alias&&Q.add(q.alias)}),Array.from(Q)}if(l.records.length>0){const Q=l.records[0],q=Object.keys(Q),H=new Set;(A=t==null?void 0:t.config)!=null&&A.groupByColumns&&t.config.groupByColumns.forEach(_=>{H.add(_.label||_.name),H.add(_.alias||_.name)});const $=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(_=>{const Y=_.alias||_.name;$.add(Y),$.add(`${Y}_count`),$.add(`${Y}_sum`),$.add(`${Y}_avg`),$.add(`${Y}_min`),$.add(`${Y}_max`);const J=_.entityName||_.qualifiedEntityName;J&&($.add(`${J}_${Y}`),$.add(`${J}_${Y}_count`))}),q.filter(_=>!H.has(_)&&!$.has(_))}}if((I||E)&&!C&&((U=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&U.length))return t.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if((ee=(W=t==null?void 0:t.config)==null?void 0:W.groupByColumns)!=null&&ee.length){const Q=t.config.groupByColumns[0],q=Q.label||Q.name,H=new Set;return l.records.forEach($=>{const F=$[q];F!=null&&H.add(String(F))}),Array.from(H)}return[]},[l,(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),f=M.useMemo(()=>s.getDefaultChartColors(),[]);M.useEffect(()=>{const E={};h.forEach((I,C)=>{E[I]=s.getColorForValue(I,C,n==null?void 0:n.colorConfig)}),c(E)},[h,n==null?void 0:n.colorConfig,f]);const g=(E,I)=>{const C={...o,[E]:I};c(C);const L={...n||{},colorConfig:{segments:C}};a(L);const A={...t,preferences:L};r(A)},j=(E,I)=>{var U;const C=f[I%f.length],{[E]:L,...A}=((U=n==null?void 0:n.colorConfig)==null?void 0:U.segments)||{},P={...n||{},colorConfig:{segments:A}};a(P);const V={...t,preferences:P};r(V),c(W=>({...W,[E]:C}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:v.length)||((T=(k=t==null?void 0:t.config)==null?void 0:k.pivotByColumns)==null?void 0:T.length):(D=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:D.length)||["table","kpi","text","custom"].includes(t.type))return null;const x=()=>{const E={...n||{},colorConfig:{segments:{}}};a(E);const I={...t,preferences:E};r(I);const C={};h.forEach((L,A)=>{C[L]=s.getColorForValue(L,A,void 0)}),c(C)},b=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:b&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:x,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((E,I)=>{const C=s.isDefaultColor(o[E],I),L=!C;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===E,onOpenChange:A=>d(A?E:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[E]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((A,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[E]===A?"border-gray-900":"border-transparent"),style:{backgroundColor:A},onClick:()=>{g(E,A),d(null)},children:[P===I%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:A})]},`default-${P}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Wl.map((A,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[E]===A?"border-2 border-gray-900":A==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:A},onClick:()=>{g(E,A),d(null)},children:e.jsx("span",{className:"sr-only",children:A})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:E,color:o[E]}),d(null)},children:"Custom color"}),!C&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(E,I),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:E}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},E)})}),m&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Tn,{color:m.color,onColorChange:E=>{g(m.value,E),u(null)},onClose:()=>u(null)})})]})]})})]})}function Ne({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const m=()=>{n(o),d(!1)},u=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),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&&o!==t?m():h.key==="Escape"&&u()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,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:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Jl=["auto","number","currency","percent","scientific","date"],Xl=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],Zl=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],eo=t=>t.charAt(0).toUpperCase()+t.slice(1);function nt({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jl.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":eo(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Zl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function kt({axis:t,label:n,type:a,config:r,onChange:l}){var h,f,g,j,p,y,x,b,w,R,N,S;const o=(v,k)=>{l({...r,[v]:k})},c=(v,k)=>{var T,O;l({...r,name:{enabled:v==="enabled"?k:((T=r==null?void 0:r.name)==null?void 0:T.enabled)??!1,text:v==="text"?k:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(v,k)=>{var T,O;l({...r,labels:{enabled:v==="enabled"?k:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)??!0,rotation:v==="rotation"?k:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},d=(v,k)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:k===""?"auto":Number(k)}})},m=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(Ne,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((y=r==null?void 0:r.labels)==null?void 0:y.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(nt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((x=r==null?void 0:r.scale)==null?void 0:x.min)==="auto"||((b=r==null?void 0:r.scale)==null?void 0:b.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function In(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const m={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(m);const u={...t,preferences:m};r(u)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(kt,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(kt,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function An(){const t=s.useEditorStore(m=>m.card),n=s.useEditorStore(m=>{var u,h,f,g;return(g=(f=(h=(u=m.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(m,u)=>{const h={...n,[m]:u};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:m=>c("display",m)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:m=>c("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:m=>c("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function Mn(){var k,T,O,D,B,E,I,C,L;const t=s.useEditorStore(A=>A.card),n=s.useEditorStore(A=>{var P,V;return(V=(P=A.card)==null?void 0:P.preferences)==null?void 0:V.dataLabelsConfig}),a=s.useEditorStore(A=>{var P;return(P=A.card)==null?void 0:P.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((k=a==null?void 0:a.chartOptions)==null?void 0:k.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,m=(O=(T=a==null?void 0:a.chartOptions)==null?void 0:T.plugins)==null?void 0:O.datalabels,u=(m==null?void 0:m.display)!==!1&&((m==null?void 0:m.anchor)||(m==null?void 0:m.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:u,f=(A,P)=>{const V={...n,[A]:P},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},g=(A,P)=>{const V={...n,font:{...n==null?void 0:n.font,[A]:P}},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},j=(A,P)=>{const V={...n,formatOptions:{...n==null?void 0:n.formatOptions,[A]:P}},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},y=(()=>{const A=t.type;return A==="stackedBar"||A==="stackedLine"||A==="pie"||A==="doughnut"?"center":o?"right":"top"})();let x=[];c||i?x=["center"]:x=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(P=>P!==y),"custom"];const b=()=>s.titleCase(y),w=["center","start","end"],R=["center","start","end","top","bottom"],N=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:A=>f("enabled",A)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:A=>f("position",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"?b():A==="custom"?"Custom (Advanced)":s.titleCase(A)},A))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:A=>f("showTotal",A)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:A=>f("anchor",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:A=>f("align",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:A=>f("format",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"&&d?"Auto (Use Axis)":A==="none"?"None (Raw Value)":s.titleCase(A)},A))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String(((D=n==null?void 0:n.formatOptions)==null?void 0:D.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:A=>j("decimalPlaces",Number(A)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:A=>j("currency",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((E=n==null?void 0:n.formatOptions)==null?void 0:E.useSuffix)??!1,onCheckedChange:A=>j("useSuffix",A)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((I=n==null?void 0:n.formatOptions)==null?void 0:I.locale)||"en-US",onValueChange:A=>j("locale",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"12",value:String(((C=n==null?void 0:n.font)==null?void 0:C.size)||12),onSave:A=>g("size",Number(A)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:A=>g("weight",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:A=>{A==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:A=>f("rotation",Number(A)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function so(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(En,{}),e.jsx(In,{}),e.jsx(An,{}),e.jsx(Mn,{})]})]})}const to=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."]})]}),no=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."]})]}),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 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(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(so,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Gl,{}));case"tornado":case"pyramid":return l(e.jsx(ss,{docContent:to,cardType:a}));case"kpi":return e.jsx(Vl,{});case"line":case"bar":return l(e.jsx(Ll,{cardType:a}));case"range":return l(e.jsx(ss,{docContent:no,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ss,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Rl,{cardType:a}));case"table":return e.jsx(Hl,{cardType:a});case"text":return e.jsx(ss,{docContent:ao,cardType:a,suffix:"Visual"});case"map":return e.jsx(ql,{});case"custom":return e.jsx(El,{});default:return l(e.jsx(Fl,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Ln({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(fe,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const lo=[{label:"Sum",value:"SUM",logo:e.jsx(zt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Be,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(va,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(na,{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:n}=s.useEditorActions();let a=lo;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Xe(t.name,l)};n(t.id,o)}return e.jsx(Ln,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const io=[{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 co({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:Ge(t.name,r)};n(t.id,l)}return e.jsx(Ln,{column:t,functions:io,onFunctionChange:r=>a(r),label:"Granularity"})}function uo({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let i=[];(a===Le||a===Re||a===Oe)&&(i=r);const d=i==null?void 0:i.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(m=>{var u;return m.column_name===((u=i[0])==null?void 0:u.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Rn({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(kn,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Dn,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function mo({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:u,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),p=f?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,y=s.isTextDataType(t.type);function x(S){const v=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),T=s.isDateDataType(S.data_type),O=v?"number":k?"string":T?"date":"string";if(r===Le){if(k){const D={id:t.id,name:S.column_name,type:O,role:"groupby"};c(t.id,D)}if(T){const D={id:t.id,name:S.column_name,type:O,role:"groupby",label:Ge(S.column_name,"month"),granularity:"month"};c(t.id,D)}}if(r===Oe){if(k){const D={id:t.id,name:S.column_name,type:O,role:"groupby"};d(t.id,D)}if(T){const D={id:t.id,name:S.column_name,type:O,label:Ge(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,D)}}if(r===Re){const D={id:t.id,name:S.column_name,type:O,role:"metric",label:Xe(S.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,D)}}function b(){if(r===Re)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(Rn,{column:t})})}function w(){const S=s.isDateDataType(t.type);if(r===Re)return e.jsx(oo,{column:t});if((r===Le||r===Oe)&&S)return e.jsx(co,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Le||r===Oe)&&y}),children:e.jsx(uo,{col:t,onChange:x,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx($a,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Bt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:p,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:[N(),w(),R()]}),l&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function ks({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,y;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(x=>x.activeId),u=s.useEditorStore(x=>{var b;return(b=x.card)==null?void 0:b.type}),h=i||((y=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:y.type)===l,f=m?r:a,g=l===is?"Rows":l===cs?"Pivot Columns":"Columns";function j(){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:a==null?void 0:a.map(x=>x.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),u!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(x=>x.id===cn.id?e.jsx(ho,{},x.id):e.jsx(mo,{droppableId:t,type:l,column:x,onRemoveColumn:o},x.id))})]})})}function ho(){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 On({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),m=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:m,children:t})}function xo(){const t=s.useEditorStore(x=>{var b;return(b=x.card.queryConfig)==null?void 0:b.orderBy})||[],n=s.useEditorStore(x=>{var b;return(b=x.card.queryConfig)==null?void 0:b.groupByColumns})||[],a=s.useEditorStore(x=>{var b;return(b=x.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(x=>!t.some(b=>b.columnId===x.id)).map(x=>({id:x.id,value:x.label||x.name}));function f(x,b){const w=g(x);return w?w.role==="metric"?b==="asc"?m:u:b==="asc"?i:d:null}function g(x){return c.find(b=>b.id===x)}function j(x){const b=t.find(w=>w.columnId===x);if(b){const w={...b,direction:b.direction==="asc"?"desc":"asc"};o(w)}}const p=x=>{r({columnId:x.id,direction:"asc"})};function y(x){const b=t.find(w=>w.columnId===x);b&&l(b)}return e.jsx(s.SortableContext,{items:t.map(x=>Ke(x.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:x=>p(x[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(x=>{var b,w;return e.jsx(On,{id:Ke(x.columnId),type:Ks,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(Bt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(gs,{className:"w-[175px] text-sm",children:((b=g(x.columnId))==null?void 0:b.label)||((w=g(x.columnId))==null?void 0:w.name)})]}),e.jsx("button",{title:x.direction==="asc"?"Ascending":"Descending",onClick:()=>j(x.columnId),className:"rounded-sm p-0",children:f(x.columnId,x.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>y(x.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"})})})]})},x.columnId)},Ke(x.columnId))})]})})}function po(){const t=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.groupByColumns)||[]}),n=s.useEditorStore(y=>y.card.type),a=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function u(y){i(y)}function h(y){d(y)}function f(y){m(y)}let g="Group By",j="Metrics",p="Stack By";return n==="table"&&(g="Rows",j="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(vn,{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(ks,{onRemoveColumn:u,sortableType:is,id:Le,label:g,columns:t,previewColumns:a}),e.jsx(ks,{onRemoveColumn:f,sortableType:cs,id:Oe,label:p,columns:o,previewColumns:c}),e.jsx(ks,{onRemoveColumn:h,sortableType:Ls,id:Re,label:j,columns:r,previewColumns:l}),e.jsx(xo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function at({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function u(h){i(h)}return e.jsx(On,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),m&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>u(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function fo({column:t,sortableType:n}){const a=s.useDashboardStore(w=>w.themeStyle),r=s.useEditorStore(w=>{var R,N;return(N=(R=w.card)==null?void 0:R.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(w=>{var R,N;return(N=(R=w.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:N.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var w;return(w=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:w.filterValue},[r,t.name]),m=M.useMemo(()=>Array.isArray(d)?d.map(w=>({id:w,value:w})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:j,isError:p}=s.useFilterQuery(h),y=M.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(N=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[S]===void 0&&(S=S.toLowerCase()),{id:N[S],value:N[S]}}):[]},[f,h.column]);function x(w){const R=w.map(N=>N.id);u(t.name,R)}function b(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?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(go,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:x,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(at,{className:"w-60",id:t.id,sortableType:n,column:t,children:b()})}function go({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function jo({column:t,sortableType:n}){const[a,r]=M.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:m,isError:u,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:p}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:y}=s.useEditorActions();function x(R){var S,v;const N={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(v=R==null?void 0:R.to)==null?void 0:v.toISOString()};y(t.name,N)}function b(){y(t.name,null,!0),j(p)}function w(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:x,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(at,{className:"w-72",id:t.id,sortableType:n,column:t,children:w()})}function yo({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var j,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(y=>y.activeId),m={},u=c||((p=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(y){const x=s.isDateDataType(y.type);return y.id===cn.id?e.jsx(at,{id:y.id,sortableType:l,column:y,children:e.jsx(vo,{})},y.id):x?e.jsx(jo,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(fo,{droppableId:t,sortableType:l,column:y},y.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(y=>f(y))})]})})}function vo(){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 bo(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(yo,{onRemoveColumn:r,sortableType:Os,id:Rs,label:"Filters",columns:t,previewColumns:n})})}function No(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l}=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(ps,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(hn,{sql:r==null?void 0:r.sql,error:l})]}),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(Ws,{}),e.jsx(Qs,{variant:"default"})]})]})}function Co(){const t=M.useRef(null),n=M.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,m,u;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=n.current)==null||u.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(xl,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(ro,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(es,{})})]}):e.jsx(es,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(po,{})})}),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(No,{}),e.jsx(bo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(es,{})})]})})]}):e.jsx(es,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function So(t){const n=s.useAIInteractionStore(z=>z.currentAIContext),[a,r]=M.useState(""),[l,o]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.python}),{setCardPython:u,setCardSql:h,setRunSql:f,switchCardType:g,setQueryConfig:j}=s.useEditorActions(),p=s.useEditorStore(z=>z.currentAssitantScope)||[],y=s.useEditorStore(z=>z.userInputForAI),x=s.useEditorStore(z=>z.triggerAIRun),b=s.useEditorStore(z=>z.card),w=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),N=s.useEditorStore(z=>z.selectedConnectionId),S=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:k,refetch:T,data:O}=s.useDashboardCardQuery(b),{setTriggerAIRun:D,setCurrentAssitantScope:B,setCardConfig:E}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:C,selectedDatamodelId:L}=s.useEditorAside(),{messages:A,setMessages:P,reload:V,error:U,append:W,input:ee,setInput:Q,status:q,handleInputChange:H,handleSubmit:$,stop:F}=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:n},maxSteps:10,onError:z=>{console.log("on error",z)},onToolCall:_,onFinish(z,X){Y(X.usage),r(""),X.finishReason==="stop"&&r("")}});M.useEffect(()=>{x&&y&&(W({role:"user",content:y}),D(!1))},[x,y,W,D]);async function _({toolCall:z}){var X,le,ye,ve;if(["createChartFromSql","createForecast"].includes(z.toolName)){const se=z.args.sql,ce=z.args.python,de=z.args.chartType;return g(de),h(se),u(ce),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),ne(),{status:"success",tables:p};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const se=z.args.chartType,ce=z.args.queryConfig;z.args.cardConfig,g(se),E(ce),h(void 0),u(void 0);const de=await T();return(X=de==null?void 0:de.data)!=null&&X.error?{status:"error",queryConfig:ce,message:(le=de==null?void 0:de.data)==null?void 0:le.error.message}:(ye=de==null?void 0:de.data)!=null&&ye.records?{status:"success",queryConfig:ce,message:"The data has been visualized"}:{status:"success",queryConfig:ce,message:"The data has been visualized",records:(ve=de==null?void 0:de.data)==null?void 0:ve.records}}else r("Analyzing...")}}function Y(z){o(X=>X?{promptTokens:X.promptTokens+z.promptTokens,completionTokens:X.completionTokens+z.completionTokens,totalTokens:X.totalTokens+z.totalTokens}:z)}function J(z){const X=s.removeFromScopeArray(p,z);te(X)}function te(z){const X=s.sanitizeAIScope(z);B(X),P(le=>[...le,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(X)}`}])}function re(){const z={databaseName:w||"",schemaName:S||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(I),connectionId:N||"",connectionType:C||""},X=s.dedup([...p,z]);te(X)}function ne(){const z={databaseName:w||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:N||"",connectionType:C||"",datamodelId:L||""};if(!s.isInAiScopeArray([...v||[],...p],z)||p.length===0){const le=s.dedup([...v||[],...p,z]).filter(ye=>ye.connectionId===z.connectionId);te(le)}}const ue=!["ready","error"].includes(q),K=s.getErrorMessage(U);return{messages:A,setMessages:P,reload:V,append:W,input:ee,setInput:Q,isLoading:ue,handleSetAIScope:ne,handleAddCurrentTableToScope:re,removeFromCurrentSelections:J,currentAssitantScope:p,setCurrentAssitantScope:B,handleInputChange:H,handleSubmit:$,stop:F,chatStatus:q,toolStatus:a,llmUsage:l,onFinish:t,errorMessage:K}}const wo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Dt(){const t=M.useRef(null),n=M.useRef(null),[a,r]=M.useState(!1),[l,o]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,m]=M.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),f=s.useDashboardStore(F=>F.dashboard.aiContext),g=s.useEditorStore(F=>F.card.dataSource),j=s.useEditorStore(F=>F.actions.setCardSql),p=s.useEditorStore(F=>F.actions.setRunSql),y=s.useEditorStore(F=>F.showAIDialog),x=s.useDashboardStore(F=>F.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:w}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:N}=s.useAssistantProfile(),{messages:S,setMessages:v,reload:k,append:T,input:O,setInput:D,isLoading:B,handleInputChange:E,handleSubmit:I,stop:C,chatStatus:L,llmUsage:A,errorMessage:P}=So();s.useAssistantScroll({scrollContainerRef:t,inputRef:n,messages:S}),M.useEffect(()=>{var F;y&&((F=n.current)==null||F.focus(),h({selectedEntities:(g==null?void 0:g.selectedEntities)||[]}))},[y,g,h]);function V(F,_){_==="sql"?(j(F),p(!0)):_==="python"&&(w(F),p(!0))}function U(){var F;(F=f==null?void 0:f.selectedEntities)==null||F[0],m(!0)}function W(){u.selectedEntities.length===0&&h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function ee(F){W();const _={role:"user",content:F.title+" "+F.subtitle};T(_)}function Q(F){W(),T({role:"user",content:F})}function q(){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:a,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function H(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(O==null?void 0:O.length)===0&&(S==null?void 0:S.filter(F=>F.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:[H(),x&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:x,children:(N==null?void 0:N.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:U,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:()=>{v([]),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:l,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:L,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[$&&!N&&e.jsx(s.Placeholders,{onClick:ee,placeholders:wo}),e.jsx("div",{children:$&&N&&e.jsx(s.SeedQuestions,{seedQuestions:N.seedQuestions||[],handleSeedQuestionClick:Q})})]}),e.jsx(s.ChatInputWithContext,{ref:n,setInput:D,stop:C,input:O,handleInputChange:E,handleSubmit:F=>{W(),I(F)},isLoading:B,onFocus:()=>{}}),A&&a&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",A.promptTokens," prompt tokens,"," ",A.completionTokens," completion tokens,"," ",A.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(g==null?void 0:g.selectedEntities)||[],open:d,onOpenChange:m,dataSource:g||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const rt=t=>{var D;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,f=M.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,dateFormat:E.dateFormat,customFormat:E.customFormat,granularity:E.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,direction:E.direction}));case"source":return[];default:return[]}},[t]),g=M.useCallback((B,E)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:E});break}case"metrics":{n(h,{metricColumns:E});break}case"pivotBy":{n(h,{pivotByColumns:E});break}case"sortBy":{n(h,{sortByColumns:E});break}}},[h,n]),j=M.useCallback((B,E,I)=>{if(!h)return;const L=f(B)[E];if(L)switch(B){case"groupBy":a(h,L.id,{label:I});break;case"metrics":r(h,L.id,{label:I});break;case"pivotBy":l(h,L.id,{label:I});break;case"sortBy":o(h,L.id,{label:I});break}},[h,f,a,r,l,o]),p=M.useCallback((B,E)=>{if(!h)return;const C=f("metrics")[B];C&&r(h,C.id,{aggregate:E,label:s.getAggregationLabel(C.name,E)})},[h,f,r]),y=M.useCallback((B,E,I)=>{if(!h)return;const L=f("groupBy")[B];if(!L)return;const A={dateFormat:E};E==="custom"&&I?A.customFormat=I:A.customFormat=void 0,a(h,L.id,A)},[h,f,a]),x=M.useCallback((B,E)=>{if(!h)return;const C=f("groupBy")[B];C&&a(h,C.id,{granularity:E})},[h,f,a]),b=M.useCallback((B,E)=>{if(!h)return;const C=f("metrics")[B];C&&r(h,C.id,{aliasTemplate:E})},[h,f,r]),w=M.useCallback((B,E)=>{if(console.log("handleValueAliasesChange",B,E),!h)return;console.log("handleValueAliasesChange",B,E);const C=f("metrics")[B];C&&(console.log("handleValueAliasesChange",E),r(h,C.id,{valueAliases:E}))},[h,f,r]),R=M.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),N=M.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),S=M.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=M.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),k=M.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),T=M.useCallback(B=>{var V;if(!h)return;const E=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,C=s.validateEntityConsistency(B,E,I);if(!C.isValid){C.showError&&s.showJoinRequiredNotification();return}const L=s.getSmartContainerForField(B,E),A=f(L);if(s.fieldAlreadyExists(B,A))return;const P=s.getNewField(B,L,A);P&&g(L,[...A,P])},[h,(D=t==null?void 0:t.config)==null?void 0:D.joinPlan,f,g]),O=M.useCallback((B,E)=>{if(!h)return;const C=f(B)[E];if(C){if(B!=="sortBy"){const L=f("sortBy"),A=L.filter(P=>!(P.name===C.name&&P.qualifiedEntityName===C.qualifiedEntityName));A.length!==L.length&&n(h,{sortByColumns:A})}switch(B){case"groupBy":c(h,C.id);break;case"metrics":i(h,C.id);break;case"pivotBy":d(h,C.id);break;case"sortBy":m(h,C.id);break}}},[h,f,c,i,d,m,n]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:x,handleAliasTemplateChange:b,handleValueAliasesChange:w,removeField:O,handleFieldClick:T,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:k,cardType:u}};function ko({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 Do({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),m=s.useEditorStore(j=>j.card),{handleFieldClick:u}=rt(m),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=j=>{const p=(j||"").toLowerCase();switch(s.getDataType(p)){case"number":return Be;case"date":return s.Calendar;case"boolean":return Je;case"json":return Es;case"geo":return Is;default:return Fe}},g=j=>{const p=(j||"").toLowerCase(),y=s.getDataType(p);return y==="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(Fe,{className:"h-3 w-3"})}):y==="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(Be,{className:"h-3 w-3"})}):y==="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"})}):y==="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(Je,{className:"h-3 w-3"})}):y==="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(Es,{className:"h-3 w-3"})}):y==="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(Is,{className:"h-3 w-3"})}):y==="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(Bs,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[g(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(ko,{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(Vt,{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(Ha,{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 To(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useEditorStore(w=>w.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(w=>w.name.toLowerCase().includes(t.toLowerCase())||w.dataType.toLowerCase().includes(t.toLowerCase())||w.qualifiedEntityName&&w.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=w=>{if(w.dataType==="number"||w.dataType==="integer"||w.dataType==="float"||w.dataType==="decimal"||w.dataType==="currency")return"metrics";const R=s.getDataType(w.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(a==="all"?m:m.filter(w=>u(w)===a)).reduce((w,R)=>{const N=R.qualifiedEntityName||"Other Fields";return w[N]||(w[N]={label:s.toLabel(R.entityName),fields:[]}),w[N].fields.push(R),w},{}),j=Object.keys(f),p=m.filter(w=>u(w)==="dimensions").length,y=m.filter(w=>u(w)==="metrics").length,x=m.filter(w=>u(w)==="calculated").length,b=m.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):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"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:w=>n(w.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:w=>r(w),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:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Bs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(f).map(([w,R])=>{const N=c.find(S=>S.entityName===w)||{entityName:w,label:R.label};return e.jsxs(s.AccordionItem,{value:w,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:N.label||N.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(Do,{field:S},S.id))})})]},w)})}),Object.keys(f).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function Eo(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(To,{})," "]})}function Io({initialJoinPlan:t,availableDataSources:n}){const[a,r]=M.useState(t),[l,o]=M.useState(new Set),c=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(k=>k.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=S=>{r({...a,joins:a.joins.filter(v=>v.id!==S)}),o(new Set([...l].filter(v=>v!==S)))},d=(S,v)=>{var D,B;const k=a.joins.find(E=>E.id===S);if(!k)return;const T={...k,...v},O=a.joins.map(E=>E.id===S?T:E);if((D=T.source)!=null&&D.name&&((B=T.target)!=null&&B.name)&&T.joinKeyGroups[0].keys.length===0){const E=n.find(A=>{var P;return A.name===((P=T.source)==null?void 0:P.name)}),I=n.find(A=>{var P;return A.name===((P=T.target)==null?void 0:P.name)}),C={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.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:"="},L=[...T.joinKeyGroups];L[0]={...L[0],keys:[C]},T.joinKeyGroups=L,O[O.findIndex(A=>A.id===S)]=T}r({...a,joins:O})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v>0){const k=[...a.joins],T={...k[v]},O={...k[v-1]};k[v]=O,k[v-1]=T,k.forEach((B,E)=>{B.sequence=E+1});const D={...a,joins:k};r(D)}},moveJoinDown:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v<a.joins.length-1){const k=[...a.joins],T={...k[v]},O={...k[v+1]};k[v]=O,k[v+1]=T,k.forEach((B,E)=>{B.sequence=E+1});const D={...a,joins:k};r(D)}},toggleJoinExpansion:S=>{const v=new Set(l);v.has(S)?v.delete(S):v.add(S),o(v)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(T=>T.id===S);if(v===0)return n;const k=new Set;return a.baseEntity.name&&k.add(a.baseEntity.name),a.joins.slice(0,v).forEach(T=>{k.add(T.source.name),k.add(T.target.name)}),n.filter(T=>k.has(T.name))},getAvailableTargetEntities:S=>n.filter(v=>v.name!==S),addJoinKeyGroup:S=>{const v=a.joins.find(T=>T.id===S);if(!v)return;const k=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,v,k)=>{const T=a.joins.find(D=>D.id===S);if(!T)return;const O=[...T.joinKeyGroups];O[v]={...O[v],operator:k},d(S,{joinKeyGroups:O})},removeJoinKeyGroup:(S,v)=>{const k=a.joins.find(O=>O.id===S);if(!k)return;const T=[...k.joinKeyGroups];T.splice(v,1),d(S,{joinKeyGroups:T})},addJoinKey:(S,v)=>{const k=a.joins.find(E=>E.id===S);if(!k)return;const T=n.find(E=>E.name===k.source.name),O=n.find(E=>E.name===k.target.name),D=[...k.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};D[v]={...D[v],keys:[...D[v].keys,B]},d(S,{joinKeyGroups:D})},updateJoinKey:(S,v,k,T,O)=>{const D=a.joins.find(L=>L.id===S);if(!D)return;const B=n.find(L=>L.name===D.source.name),E=n.find(L=>L.name===D.target.name),I=[...D.joinKeyGroups],C=I[v].keys[k];T==="sourceColumnName"&&B?I[v].keys[k]={...C,source:{...C.source,name:O}}:T==="targetColumnName"&&E?I[v].keys[k]={...C,target:{...C.target,name:O}}:T==="operator"&&(I[v].keys[k]={...C,operator:O}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,v,k)=>{const T=a.joins.find(D=>D.id===S);if(!T)return;const O=[...T.joinKeyGroups];O[v].keys.splice(k,1),d(S,{joinKeyGroups:O})},generateSQLPreview:()=>{const S=[...a.joins].sort((T,O)=>T.sequence-O.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
420
- FROM ${v.name}`;return S.forEach(T=>{const O=n.find(E=>E.name===T.target.name);if(!O)return;const D=T.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const I=E.keys.filter(C=>{var L,A,P,V;return((L=C.source)==null?void 0:L.name)&&((A=C.target)==null?void 0:A.name)&&((P=C.source)==null?void 0:P.entityName)&&((V=C.target)==null?void 0:V.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return I.length>1?`(${I.join(` ${E.operator} `)})`:I[0]}).filter(Boolean),B=D.length>1?D.join(" OR "):D[0]||"condition_here";k+=`
421
- ${T.joinType} JOIN ${O.name}
422
- ON ${B}`}),k},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(T=>!T.source.name||!T.target.name)||a.joins.some(T=>T.joinKeyGroups.some(O=>O.keys.length===0))||a.joins.some(T=>T.joinKeyGroups.some(O=>O.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function Ao({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:p,getAvailableSourceEntities:y,getAvailableTargetEntities:x,addJoinKeyGroup:b,updateGroupOperator:w,removeJoinKeyGroup:R,addJoinKey:N,updateJoinKey:S,removeJoinKey:v,generateSQLPreview:k,isValidConfiguration:T}=Io({initialJoinPlan:t,availableDataSources:n}),O=D=>{const B=c.find(E=>E.entityName===D);return(B==null?void 0:B.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 B=n.find(E=>E.name===D);m({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:D,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.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:u,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 B=n.find(C=>C.name===D.source.name),E=n.find(C=>C.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,B&&E&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",E.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(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:()=>j(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:()=>p(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:C=>{const L=n.find(A=>A.name===C);f(D.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:C,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(D.id).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name]})},C.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:C=>f(D.id,{joinType:C}),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:C=>{const L=n.find(A=>A.name===C);f(D.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:C,database:L==null?void 0:L.database,schema:L==null?void 0:L.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?x(D.source.name).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,C.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},C.name)):[]})]})]})]}),D.source.name&&D.target.name&&B&&E&&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((C,L)=>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 ",L+1]}),L>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:C.operator,onValueChange:A=>w(D.id,L,A),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,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[C.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:C.keys.map((A,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:C.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:A.source.name,onValueChange:V=>S(D.id,L,P,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:O(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:A.operator,onValueChange:V=>S(D.id,L,P,"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:A.target.name,onValueChange:V=>S(D.id,L,P,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:O(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:()=>v(D.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},A.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(D.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},C.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(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!T(),children:"Save"})]})]})}function Tt({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ao,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Mo({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(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((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Lo(){var u,h;const t=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.actions.updateCardConfig),a=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{n(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const f=[...a.joins].sort((p,y)=>p.sequence-y.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
423
- FROM ${g.name}`;return f.forEach(p=>{const y=o.find(w=>w.name===p.target.name);if(!y)return;const x=p.joinKeyGroups.filter(w=>w.keys&&w.keys.length>0).map(w=>{const R=w.keys.filter(N=>{var S,v,k,T;return((S=N.source)==null?void 0:S.name)&&((v=N.target)==null?void 0:v.name)&&((k=N.source)==null?void 0:k.entityName)&&((T=N.target)==null?void 0:T.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return R.length>1?`(${R.join(` ${w.operator} `)})`:R[0]}).filter(Boolean),b=x.length>1?x.join(" OR "):x[0]||"condition_here";j+=`
418
+ `;N(U)}function A(){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(ml,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(dl,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(ul,{})}),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:E||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[E||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(hn,{sql:v==null?void 0:v.sql,error:C,onDebugWithAssistant:L}),e.jsx(ps,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:U=>a(U),className:"",size:"sm",children:e.jsx(cl,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!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(Ws,{}),e.jsx(Qs,{})]})]})}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:[P(),A()]}),V()]})}function pl({data:t}){var c;const[n,a]=M.useState([]),l=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const m=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,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),o=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:a,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:n}});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:o.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=o.getRowModel().rows)!=null&&c.length?o.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:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function fl({card:t}){var N,k,R,b,S,v,E,w,O,D,F;const[n,a]=M.useState(!1),[r,l]=M.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(T=>T.themeStyle),d={colors:((k=(N=i==null?void 0:i.chart)==null?void 0:N.dataset)==null?void 0:k.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:m}=s.useCustomVisual(((b=t.customCardPreferences)==null?void 0:b.url)||""),u=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=M.useCallback((T,I)=>{l(C=>({...C,[T]:I}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const p=m((E=t.customCardPreferences)==null?void 0:E.componentName);function y(T){a(T)}const x=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(T=>{var L,A,P;const I=(A=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:A[T].cardId,C=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===I);return C||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:[p&&u==="single"&&e.jsx(p,{editing:!0,params:c,theme:d,settings:(O=t.customCardPreferences)==null?void 0:O.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),p&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((D=t.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(T=>{var L,A,P;const I=(A=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:A[T].cardId,C=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===I);if(C)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:T,card:C},C.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:d,onDataChange:j,settings:x.map(T=>{var I;return(I=T==null?void 0:T.customCardPreferences)==null?void 0:I.settings}),data:x.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(F=t.customCardPreferences)==null?void 0:F.componentName)})}function gn({className:t,...n}){var E;const a=s.useEditorStore(w=>w.card),r=s.isExplorerCard(a),l=((E=a.customCardPreferences)==null?void 0:E.showCardHeader)??!0,o=s.useEditorStore(w=>w.frame),c=s.useDashboardStore(w=>w.dashboard.filters),i=s.useEditorStore(w=>w.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(w=>w.id===o.filterId),{data:u,isLoading:h,isFetching:f,errorMessage:g,pagination:j,refetch:p}=s.useDashboardCardQuery(a),{setCard:y,updateCardInFrame:x}=s.useEditorActions(),{data:N}=s.useTopoJson(a),k=M.useMemo(()=>a.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:a,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[a,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),R=(w,O)=>{var F,T;const D={...a,paginationConfig:{page:w+1,pageSize:O}};y(D),x(D),a.sql&&((T=(F=a.preferences)==null?void 0:F.tablePrefs)!=null&&T.enableDevModePagination)&&i(!0)},b=M.useMemo(()=>!a.id||!(u!=null&&u.records)?null:s.createChartConfig({card:a,data:u==null?void 0:u.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:N}),[a.id,u==null?void 0:u.records,a.type,a.queryConfig,a.customCfg,a.preferences,N]);function S(w){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(fl,{card:w})})}function v(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return S(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&b)return e.jsx(e.Fragment,{children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:b})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(u==null?void 0:u.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||f})});if(a.type==="pivotTable"&&k)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.PivotTableVisual,{card:a,data:k.data,options:k.options,onAggregationChange:w=>{const O=s.handleAggregationChange(w,a.config),D={...a,config:O};y(D),x(D)},onAggregationLabelChange:w=>{const O=s.handleAggregationLabelChange(w,a.config),D={...a,config:O};y(D),x(D)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(u==null?void 0:u.records)||[],groupByColumns:u==null?void 0:u.groupByColumns,pivotSchema:u==null?void 0:u.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:w=>{const O=s.handleAggregationChange(w,a.config),D={...a,config:O};y(D),x(D)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:a.title,onSave:w=>y({...a,title:w}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:a.title||"Add title"})})},a.title),e.jsx(s.Editable,{enabled:!0,text:a.description||"",onSave:w=>y({...a,description:w}),children:e.jsx(s.CardDescription,{children:a.description||"Add description"})},a.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:w=>d({...m,title:w}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const Ss=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),gl=()=>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."})]})]}),jl=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ss,{language:"javascript",value:t,onChange:l})})]}),yl=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function vl(){const[t,n]=M.useState(!1),[a,r]=M.useState(""),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(""),u=s.useEditorStore(b=>b.card),h=s.useEditorStore(b=>b.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(u),{data:j}=s.useTopoJson(u),{setCardCustomCfg:p,setCustomVisualCode:y}=s.useEditorActions(),x=b=>{var S,v;return JSON.stringify({...b,data:{...b.data,datasets:(v=(S=b.data)==null?void 0:S.datasets)==null?void 0:v.map(E=>({...E,data:[]}))}},null,2)},N=()=>{var S,v;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const b=s.createChartConfig({card:u,data:g.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:j});if(b){r(x(b)),i(((v=u.preferences)==null?void 0:v.customVisualCode)||"");const E=s.merge(b,h);o(x(E))}},k=()=>{try{if(c&&y(c),l){const b=JSON.parse(l),S=s.getObjectDiff(JSON.parse(a),b);p(S),m("")}}catch{m("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:N,className: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(gl,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(gn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(jl,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:b=>o(b??""),onCodeChange:b=>i(b??"")})]}),e.jsx(yl,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:k,onClose:()=>n(!1)})]})]})}function fs(t){const[n,a]=M.useState(null);return n}function jn(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:n,isLoading:a,isFetching:r,isError:l}}function yn(){const{data:t,isLoading:n,isError:a}=jn(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var m;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((m=t==null?void 0:t.plugins)!=null&&m[d])){const u=t.plugins[d],h=i.data.visuals.map(f=>({name:f.name,pluginName:u.label,componentType:f.componentType,pluginType:u.type,icon:f.icon,chartType:f.chartType,url:u.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function bl({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=yn(),d=M.useCallback((m,u)=>{n(null),a({}),r(m),u&&l({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((m,u)=>e.jsx(Nl,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},`${m.url}-${m.name}-${u}`))})]})}const Nl=({text:t,icon:n,onClick:a})=>{const r=fs(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Js(t){return ze({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 Cl(t){return ze({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 Xs(t){return ze({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 Zs(t){return ze({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 et(t){return ze({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 st(t){return ze({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 vn({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(u,h){o(null),r({}),a(u),["custom","text","map"].includes(u)&&(l(!0),i(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Ye,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Bs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(et,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(zs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Xs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Vs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Us,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Js,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx($s,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ps,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(st,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Lt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(_s,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Qe,{className:s.cn("size-5",n)})})]})}function Sl({chartType:t,className:n,customIcon:a,componentName:r}){const l=fs();switch(t){case"bar":return e.jsx(ms,{className:n});case"line":return e.jsx(hs,{className:n});case"pie":return e.jsx(xs,{className:n});case"radar":return e.jsx(Us,{className:n});case"scatter":return e.jsx(zs,{className:n});case"bubble":return e.jsx(Xs,{className:n});case"doughnut":return e.jsx(Vs,{className:n});case"stackedBar":return e.jsx(Bs,{className:n});case"stackedLine":return e.jsx(et,{className:n});case"polarArea":return e.jsx(Js,{className:n});case"funnel":return e.jsx(Zs,{className:n});case"tornado":case"pyramid":return e.jsx($s,{className:n});case"range":return e.jsx(Ps,{className:n});case"kpi":return e.jsx(st,{className:n});case"text":return e.jsx(Be,{className:n});case"map":return e.jsx(_s,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Qe,{className:n});default:return e.jsx(Ye,{className:n})}}function bn({variant:t="ghost"}){var o,c;const[n,a]=M.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Sl,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(vn,{onChartTypeChange:()=>a(!1)}),e.jsx(bl,{onChartTypeChange:()=>a(!1)})]})]})}function wl(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(ft,{className:"size-4"}):e.jsx(pt,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(ft,{className:"size-4"}):e.jsx(pt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function Nn(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(wl,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(Sa,{className:"size-4"}),r==="x"&&e.jsx(ma,{className:"size-4"}),r==="y"&&e.jsx(Va,{className:"size-4"}),r==="none"&&e.jsx(Ya,{className:"size-4"})]})]}):null}function kl(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,p)=>{j.dataTransfer.setData("tabIndex",p.toString())},i=j=>{j.preventDefault()},d=(j,p)=>{const y=j.dataTransfer.getData("tabIndex");if(y===p.toString())return;const x=Array.from(t.cards),[N]=x.splice(parseInt(y),1);x.splice(p,0,N),a({...t,cards:x})};function m(j){const p=t.cards.filter(N=>N.id!==j),y=p[0],x={...t,cards:p,activeCardId:y.id};a(x),r(y.id),l(y)}function u(j,p){const y={...t,cards:[...t.cards,p],activeCardId:j.id};a(y),r(p.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};u(n,j)}function f(j){const p={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};u(j,p)}function g(j,p){return j.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||j.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:y}),o({...p,displayTab:y})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(fa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,p),onDragOver:i,onDrop:y=>d(y,p),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...n,tabTitle:y}),o({...n,tabTitle:y})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(xa,{className:"h-4 w-4"})})]})})}function Cn(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:u,isFetching:h}=s.useDashboardCardQuery(n);function f(p){const y=t.cards.find(x=>x.id===p);if(y!=null&&y.sql){r||i(!0),o(p);return}if(y!=null&&y.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const y={...t,cards:t.cards.map(N=>N.id===n.id?n:N),activeCardId:p};l(y);const x=y.cards.find(N=>N.id===p);x.sql&&d(!0),c(x)}function j(){return n.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:m==null?void 0:m.records,isPending:u||h})})}):n.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(gn,{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(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:j()},p.id)),e.jsx(kl,{})]})}function es({children:t}){var R,b;s.useEditorStore(S=>S.frame);const n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:j,errorMessage:p,refetch:y}=s.useDashboardCardQuery(n);function x(){const S=JSON.stringify(f==null?void 0:f.records,null,2),v=new Blob([S],{type:"application/json"}),E=URL.createObjectURL(v),w=document.createElement("a");w.href=E,w.download=`${n.title}.json`,w.click()}function N(){const v=[Object.keys(f==null?void 0:f.records.reduce((D,F)=>({...D,...F}),{})).join(","),...((f==null?void 0:f.records)||[]).map(D=>Object.values(D).join(","))].join(`
419
+ `),E=new Blob([v],{type:"text/csv"}),w=URL.createObjectURL(E),O=document.createElement("a");O.href=w,O.download=`${n.title}.csv`,O.click()}function k(){const S=`Can you get the documentation for ${n.type} chart?`;m(S)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(bn,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(oa,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(vl,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:N,children:e.jsx(Cl,{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(ja,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.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(Nn,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((b=(R=n.preferences)==null?void 0:R.tablePrefs)==null?void 0:b.enableDevModePagination)??!1,onCheckedChange:S=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:S}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Tl,{})]}),r?e.jsx(Cn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(Dl,{})}),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:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(pl,{data:(f==null?void 0:f.records)||[]}),p&&e.jsx(un,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Dl(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col 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:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Tl(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function El(){var p,y;const t=s.useEditorStore(x=>x.card.customCardPreferences),{data:n}=jn(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),m=(p=d==null?void 0:d.visuals)==null?void 0:p.find(x=>x.name===(t==null?void 0:t.componentName));function u(x,N){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[x]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:R})}function h(x){var k,R;const N=(k=l==null?void 0:l.cards)==null?void 0:k.filter(b=>{var S;return((S=b==null?void 0:b.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(b=>({value:b.id,label:b.tabTitle||b.title}));return e.jsx("div",{className:"space-y-2",children:(R=x==null?void 0:x.dataInputs)==null?void 0:R.map((b,S)=>{var v,E;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:b}),e.jsx(fe,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((E=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[S])==null?void 0:E.cardId)||"",onValueChange:w=>u(S,w)})]},S+Math.random())})})}function f(x,N,k=[],R=""){var b,S;return t?x==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((b=t==null?void 0:t.settings)==null?void 0:b[N])||R,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v.target.value}})}},N):x==="select"?e.jsx(fe,{className:"h-8 w-full",label:"",options:k,value:((S=t==null?void 0:t.settings)==null?void 0:S[N])||R,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v}})}}):null:null}function g(x){const N=Object.entries((x==null?void 0:x.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([k,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,k,R.options,R.defaultValue)]},k))})}function j(x){t&&c({...t,visualType:x,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(fe,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:x=>c({...t||{url:"",componentName:""},url:x})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(fe,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(x=>x.type===o).map(x=>({value:x.name,label:x.name})))||[],value:t.componentName,onValueChange:x=>{console.log("changing value",x),c({...t,componentName:x})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(m)})})]})]})]})}function Ve(){const[t,n]=M.useState([]),a=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),o=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),M.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(m,u){var h,f;u?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:m,expression:""}]}):l({...a,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...a,onClickFilter:(f=a==null?void 0:a.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==m)}),n(g=>{const j=[...g];return j[m]=!1,j}))}function i(m,u){var f;const h=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===m?{...g,expression:u.target.value}:g);l({...a,onClickFilter:h})}function d(m){var u,h,f,g;if(t!=null&&t[m]||(h=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(j=>j.columnIndex===m))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(j=>j.columnIndex===m))==null?void 0:g.expression,onChange:j=>i(m,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),o==null?void 0:o.map((m,u)=>{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=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===u)),onCheckedChange:g=>c(u,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[u]=!g[u],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function Il({idx:t}){var i;const n=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),a=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:m,datalabels:u}]});else{const h={...o};h.datalabels=u;const f=a==null?void 0:a.map(g=>g.idx===m?h:g);r({...n,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Vt,{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(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ia,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ea,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Al(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function gs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Sn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Al();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:wn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,m)=>e.jsx(kn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function wn(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function kn({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,f;return(f=(h=u.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(u=>u.idx===n),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...i};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(gs,{className:"max-w-[100px]",title:t,children:wn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ms,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(hs,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Rt,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Il,{idx:n})]})]})}function tt(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:u,connectionType:h}=s.useEditorAside();function f(g,j="dashboard",p){var E;const y=s.fmt(g.column_name),x=s.fmt(a||""),N=s.fmt(r||""),k=s.fmt(u);let R=s.getQualifiedTableName({schemaName:N,tableName:k,connectionType:h,databaseName:x}),b=`${R}.${y}`;const S=(E=m==null?void 0:m.find(w=>w.id===n))==null?void 0:E.name;n&&n!=="none"&&(b=`${s.DATAMODEL_NAMESPCACE}.${S}.${y}`,R=`${s.DATAMODEL_NAMESPCACE}.${S}`),p!=null&&p.qualifiedFieldName&&(b=p.qualifiedFieldName),p!=null&&p.entityName&&(R=p.entityName);const v=o==null?void 0:o.find(w=>w.column===b&&w.table===k&&(w.database===x||w.database===a));if(v)d(v.id),i(v.id);else{const w=s.v4();return u==="api"&&t?(c({location:j,id:w,column:b,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),w):(c({id:w,location:j,column:b,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),w)}}return{assignFilter:f}}function He(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=tt();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Ml,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Ml({columns:t,onSelect:n}){var c;const[a,r]=xe.useState(!1),[l,o]=xe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const m=d===l?"":d;o(m),r(!1),m&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Ll({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Sn,{})})]}),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(Ve,{}),e.jsx(He,{})]})]})]})})}function Rl({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ve,{}),e.jsx(He,{})]})]})]})})}function Dn(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var u;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(u=a==null?void 0:a.chartOptions)==null?void 0:u.plugins,...d}}};r(m)}function o(){var i,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Ol={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Fl={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Bl(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Pl(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Dn,{}),e.jsx(Ve,{}),e.jsx(He,{})]})]})}function Pl(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(Ol,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(Fl,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 zl(){var u,h,f,g,j;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.decimalPlaces});const o=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.locale}),c=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var y,x;return(x=(y=p.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),m=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((u=t==null?void 0:t.formatNumber)!=null&&u.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var y,x,N;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",p,((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var y,x,N;console.log("currency",p),l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,p==="none"?"":p,((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),m.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var y,x,N;return l(Number(p),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var y,x,N;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(s.ColorFormat,{colorRanges:i,setColorRanges:d})]})]})}function Vl(){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(zl,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ws({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const _l=[{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"}],Ul=["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"],$l=Ul.map(t=>({label:t,value:t}));function ql(){var d,m,u,h,f,g,j,p,y,x,N,k,R,b,S,v,E,w;const t=s.useEditorStore(O=>O.card),n=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[a,r]=M.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(ws,{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(ws,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(fe,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),l({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(fe,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(fe,{className:"h-9",options:_l,value:((p=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(fe,{className:"h-9",options:$l,value:((x=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:x.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ws,{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:((k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:O=>{var D;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(b=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:b.projectionOffset)==null?void 0:S[0])||0,onChange:O=>{var D,F,T,I;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[Number(O.target.value),((I=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.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=(E=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[1])||0,onChange:O=>{var D,F,T,I;l({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[((I=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:I[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ve,{})]})}function Yl(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ss({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Yl,{})})]}),!["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(Ve,{}),e.jsx(He,{})]})]})]})})}function Gl(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(fe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Sn,{})]})]}),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(Ve,{}),e.jsx(He,{})]})]})]})})}function Hl({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ve,{}),e.jsx(He,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Tn({color:t,onColorChange:n,onClose:a}){const[r,l]=M.useState(0),[o,c]=M.useState(100),[i,d]=M.useState(50),[m,u]=M.useState(t);M.useEffect(()=>{const y=St(t);if(y){const x=wt(y.r,y.g,y.b);l(x.h),c(x.s),d(x.l),u(t)}},[t]);const h=y=>{l(y),g(y,o,i)},f=y=>{const x=y.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(y.clientX-x.left)/x.width)),k=Math.max(0,Math.min(1,(y.clientY-x.top)/x.height)),R=N*100,b=(1-k)*100;c(R),d(b),g(r,R,b)},g=(y,x,N)=>{const k=Ql(y,x,N),R=Kl(k.r,k.g,k.b);u(R)},j=y=>{if(u(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const x=St(y);if(x){const N=wt(x.r,x.g,x.b);l(N.h),c(N.s),d(N.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(n(m),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:y=>{y.buttons===1&&f(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:m,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:m}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function St(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Kl(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function wt(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Ql(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(m,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(u-m)*6*h:h<.5?u:h<.6666666666666666?m+(u-m)*(.6666666666666666-h)*6:m),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Wl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function En(){var k,R,b,S,v,E,w,O,D,F;const t=s.useEditorStore(T=>T.card),n=s.useEditorStore(T=>{var I;return(I=T.card)==null?void 0:I.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=M.useState({}),[i,d]=M.useState(null),[m,u]=M.useState(null),h=M.useMemo(()=>{var L,A,P,V,U,W,ee;if(!(l!=null&&l.records)||l.records.length===0)return[];const T=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",I=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",C=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((T||I)&&C){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const Q=new Set;return l.pivotSchema.forEach(q=>{q.alias&&Q.add(q.alias)}),Array.from(Q)}if(l.records.length>0){const Q=l.records[0],q=Object.keys(Q),H=new Set;(A=t==null?void 0:t.config)!=null&&A.groupByColumns&&t.config.groupByColumns.forEach(_=>{H.add(_.label||_.name),H.add(_.alias||_.name)});const $=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(_=>{const Y=_.alias||_.name;$.add(Y),$.add(`${Y}_count`),$.add(`${Y}_sum`),$.add(`${Y}_avg`),$.add(`${Y}_min`),$.add(`${Y}_max`);const J=_.entityName||_.qualifiedEntityName;J&&($.add(`${J}_${Y}`),$.add(`${J}_${Y}_count`))}),q.filter(_=>!H.has(_)&&!$.has(_))}}if((I||T)&&!C&&((U=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&U.length))return t.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if((ee=(W=t==null?void 0:t.config)==null?void 0:W.groupByColumns)!=null&&ee.length){const Q=t.config.groupByColumns[0],q=Q.label||Q.name,H=new Set;return l.records.forEach($=>{const B=$[q];B!=null&&H.add(String(B))}),Array.from(H)}return[]},[l,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(b=t==null?void 0:t.config)==null?void 0:b.metricColumns,t==null?void 0:t.type]),f=M.useMemo(()=>s.getDefaultChartColors(),[]);M.useEffect(()=>{const T={};h.forEach((I,C)=>{T[I]=s.getColorForValue(I,C,n==null?void 0:n.colorConfig)}),c(T)},[h,n==null?void 0:n.colorConfig,f]);const g=(T,I)=>{const C={...o,[T]:I};c(C);const L={...n||{},colorConfig:{segments:C}};a(L);const A={...t,preferences:L};r(A)},j=(T,I)=>{var U;const C=f[I%f.length],{[T]:L,...A}=((U=n==null?void 0:n.colorConfig)==null?void 0:U.segments)||{},P={...n||{},colorConfig:{segments:A}};a(P);const V={...t,preferences:P};r(V),c(W=>({...W,[T]:C}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:v.length)||((w=(E=t==null?void 0:t.config)==null?void 0:E.pivotByColumns)==null?void 0:w.length):(D=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:D.length)||["table","kpi","text","custom"].includes(t.type))return null;const x=()=>{const T={...n||{},colorConfig:{segments:{}}};a(T);const I={...t,preferences:T};r(I);const C={};h.forEach((L,A)=>{C[L]=s.getColorForValue(L,A,void 0)}),c(C)},N=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ba,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:x,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((T,I)=>{const C=s.isDefaultColor(o[T],I),L=!C;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===T,onOpenChange:A=>d(A?T:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[T]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((A,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[T]===A?"border-gray-900":"border-transparent"),style:{backgroundColor:A},onClick:()=>{g(T,A),d(null)},children:[P===I%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:A})]},`default-${P}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Wl.map((A,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[T]===A?"border-2 border-gray-900":A==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:A},onClick:()=>{g(T,A),d(null)},children:e.jsx("span",{className:"sr-only",children:A})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{u({value:T,color:o[T]}),d(null)},children:"Custom color"}),!C&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(T,I),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:T}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},T)})}),m&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Tn,{color:m.color,onColorChange:T=>{g(m.value,T),u(null)},onClose:()=>u(null)})})]})]})})]})}function Ne({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const m=()=>{n(o),d(!1)},u=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),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&&o!==t?m():h.key==="Escape"&&u()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:m,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:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Jl=["auto","number","currency","percent","scientific","date"],Xl=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],Zl=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],eo=t=>t.charAt(0).toUpperCase()+t.slice(1);function nt({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jl.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":eo(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Zl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function kt({axis:t,label:n,type:a,config:r,onChange:l}){var h,f,g,j,p,y,x,N,k,R,b,S;const o=(v,E)=>{l({...r,[v]:E})},c=(v,E)=>{var w,O;l({...r,name:{enabled:v==="enabled"?E:((w=r==null?void 0:r.name)==null?void 0:w.enabled)??!1,text:v==="text"?E:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(v,E)=>{var w,O;l({...r,labels:{enabled:v==="enabled"?E:((w=r==null?void 0:r.labels)==null?void 0:w.enabled)??!0,rotation:v==="rotation"?E:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},d=(v,E)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:E===""?"auto":Number(E)}})},m=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(Ne,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((y=r==null?void 0:r.labels)==null?void 0:y.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(nt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((x=r==null?void 0:r.scale)==null?void 0:x.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((b=r==null?void 0:r.scale)==null?void 0:b.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function In(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const m={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(m);const u={...t,preferences:m};r(u)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(kt,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(kt,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function An(){const t=s.useEditorStore(m=>m.card),n=s.useEditorStore(m=>{var u,h,f,g;return(g=(f=(h=(u=m.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(m,u)=>{const h={...n,[m]:u};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:m=>c("display",m)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:m=>c("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:m=>c("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function Mn(){var E,w,O,D,F,T,I,C,L;const t=s.useEditorStore(A=>A.card),n=s.useEditorStore(A=>{var P,V;return(V=(P=A.card)==null?void 0:P.preferences)==null?void 0:V.dataLabelsConfig}),a=s.useEditorStore(A=>{var P;return(P=A.card)==null?void 0:P.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((E=a==null?void 0:a.chartOptions)==null?void 0:E.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,m=(O=(w=a==null?void 0:a.chartOptions)==null?void 0:w.plugins)==null?void 0:O.datalabels,u=(m==null?void 0:m.display)!==!1&&((m==null?void 0:m.anchor)||(m==null?void 0:m.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:u,f=(A,P)=>{const V={...n,[A]:P},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},g=(A,P)=>{const V={...n,font:{...n==null?void 0:n.font,[A]:P}},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},j=(A,P)=>{const V={...n,formatOptions:{...n==null?void 0:n.formatOptions,[A]:P}},U={...t.preferences||{},dataLabelsConfig:V};r(U);const W={...t,preferences:U};l(W)},y=(()=>{const A=t.type;return A==="stackedBar"||A==="stackedLine"||A==="pie"||A==="doughnut"?"center":o?"right":"top"})();let x=[];c||i?x=["center"]:x=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(P=>P!==y),"custom"];const N=()=>s.titleCase(y),k=["center","start","end"],R=["center","start","end","top","bottom"],b=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:A=>f("enabled",A)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:A=>f("position",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"?N():A==="custom"?"Custom (Advanced)":s.titleCase(A)},A))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:A=>f("showTotal",A)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:A=>f("anchor",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:A=>f("align",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:s.titleCase(A)},A))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:A=>f("format",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(A=>e.jsx(s.SelectItem,{value:A,className:"text-xs",children:A==="auto"&&d?"Auto (Use Axis)":A==="none"?"None (Raw Value)":s.titleCase(A)},A))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String(((D=n==null?void 0:n.formatOptions)==null?void 0:D.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:A=>j("decimalPlaces",Number(A)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:A=>j("currency",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((T=n==null?void 0:n.formatOptions)==null?void 0:T.useSuffix)??!1,onCheckedChange:A=>j("useSuffix",A)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((I=n==null?void 0:n.formatOptions)==null?void 0:I.locale)||"en-US",onValueChange:A=>j("locale",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(A=>e.jsx(s.SelectItem,{value:A.value,className:"text-xs",children:A.label},A.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"12",value:String(((C=n==null?void 0:n.font)==null?void 0:C.size)||12),onSave:A=>g("size",Number(A)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:A=>g("weight",A),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:A=>{A==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:A=>f("rotation",Number(A)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function so(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(En,{}),e.jsx(In,{}),e.jsx(An,{}),e.jsx(Mn,{})]})]})}const to=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."]})]}),no=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."]})]}),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 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(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(so,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Gl,{}));case"tornado":case"pyramid":return l(e.jsx(ss,{docContent:to,cardType:a}));case"kpi":return e.jsx(Vl,{});case"line":case"bar":return l(e.jsx(Ll,{cardType:a}));case"range":return l(e.jsx(ss,{docContent:no,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ss,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Rl,{cardType:a}));case"table":return e.jsx(Hl,{cardType:a});case"text":return e.jsx(ss,{docContent:ao,cardType:a,suffix:"Visual"});case"map":return e.jsx(ql,{});case"custom":return e.jsx(El,{});default:return l(e.jsx(Bl,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Ln({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(fe,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const lo=[{label:"Sum",value:"SUM",logo:e.jsx(zt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Fe,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(va,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(na,{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:n}=s.useEditorActions();let a=lo;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Xe(t.name,l)};n(t.id,o)}return e.jsx(Ln,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const io=[{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 co({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:Ge(t.name,r)};n(t.id,l)}return e.jsx(Ln,{column:t,functions:io,onFunctionChange:r=>a(r),label:"Granularity"})}function uo({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let i=[];(a===Le||a===Re||a===Oe)&&(i=r);const d=i==null?void 0:i.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(m=>{var u;return m.column_name===((u=i[0])==null?void 0:u.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Rn({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(kn,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Dn,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function mo({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:u,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),p=f?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,y=s.isTextDataType(t.type);function x(S){const v=s.isNumberDataType(S.data_type),E=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),O=v?"number":E?"string":w?"date":"string";if(r===Le){if(E){const D={id:t.id,name:S.column_name,type:O,role:"groupby"};c(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:O,role:"groupby",label:Ge(S.column_name,"month"),granularity:"month"};c(t.id,D)}}if(r===Oe){if(E){const D={id:t.id,name:S.column_name,type:O,role:"groupby"};d(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:O,label:Ge(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,D)}}if(r===Re){const D={id:t.id,name:S.column_name,type:O,role:"metric",label:Xe(S.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,D)}}function N(){if(r===Re)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(Rn,{column:t})})}function k(){const S=s.isDateDataType(t.type);if(r===Re)return e.jsx(oo,{column:t});if((r===Le||r===Oe)&&S)return e.jsx(co,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Le||r===Oe)&&y}),children:e.jsx(uo,{col:t,onChange:x,droppableId:r})})}function b(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx($a,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Ft,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:p,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:[b(),k(),R()]}),l&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function ks({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,y;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(x=>x.activeId),u=s.useEditorStore(x=>{var N;return(N=x.card)==null?void 0:N.type}),h=i||((y=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:y.type)===l,f=m?r:a,g=l===is?"Rows":l===cs?"Pivot Columns":"Columns";function j(){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:a==null?void 0:a.map(x=>x.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),u!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(x=>x.id===cn.id?e.jsx(ho,{},x.id):e.jsx(mo,{droppableId:t,type:l,column:x,onRemoveColumn:o},x.id))})]})})}function ho(){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 On({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),m=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:m,children:t})}function xo(){const t=s.useEditorStore(x=>{var N;return(N=x.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(x=>{var N;return(N=x.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(x=>{var N;return(N=x.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(x=>!t.some(N=>N.columnId===x.id)).map(x=>({id:x.id,value:x.label||x.name}));function f(x,N){const k=g(x);return k?k.role==="metric"?N==="asc"?m:u:N==="asc"?i:d:null}function g(x){return c.find(N=>N.id===x)}function j(x){const N=t.find(k=>k.columnId===x);if(N){const k={...N,direction:N.direction==="asc"?"desc":"asc"};o(k)}}const p=x=>{r({columnId:x.id,direction:"asc"})};function y(x){const N=t.find(k=>k.columnId===x);N&&l(N)}return e.jsx(s.SortableContext,{items:t.map(x=>Ke(x.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:x=>p(x[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(x=>{var N,k;return e.jsx(On,{id:Ke(x.columnId),type:Ks,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(Ft,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(gs,{className:"w-[175px] text-sm",children:((N=g(x.columnId))==null?void 0:N.label)||((k=g(x.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:x.direction==="asc"?"Ascending":"Descending",onClick:()=>j(x.columnId),className:"rounded-sm p-0",children:f(x.columnId,x.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>y(x.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"})})})]})},x.columnId)},Ke(x.columnId))})]})})}function po(){const t=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.groupByColumns)||[]}),n=s.useEditorStore(y=>y.card.type),a=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var x;return((x=y.card.queryConfig)==null?void 0:x.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function u(y){i(y)}function h(y){d(y)}function f(y){m(y)}let g="Group By",j="Metrics",p="Stack By";return n==="table"&&(g="Rows",j="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(vn,{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(ks,{onRemoveColumn:u,sortableType:is,id:Le,label:g,columns:t,previewColumns:a}),e.jsx(ks,{onRemoveColumn:f,sortableType:cs,id:Oe,label:p,columns:o,previewColumns:c}),e.jsx(ks,{onRemoveColumn:h,sortableType:Ls,id:Re,label:j,columns:r,previewColumns:l}),e.jsx(xo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function at({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function u(h){i(h)}return e.jsx(On,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),m&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>u(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function fo({column:t,sortableType:n}){const a=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var R,b;return(b=(R=k.card)==null?void 0:R.queryConfig)==null?void 0:b.filters}),l=s.useEditorStore(k=>{var R,b;return(b=(R=k.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:b.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var k;return(k=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),m=M.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:j,isError:p}=s.useFilterQuery(h),y=M.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(b=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return b[S]===void 0&&(S=S.toLowerCase()),{id:b[S],value:b[S]}}):[]},[f,h.column]);function x(k){const R=k.map(b=>b.id);u(t.name,R)}function N(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?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(go,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:x,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(at,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function go({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function jo({column:t,sortableType:n}){const[a,r]=M.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:m,isError:u,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:p}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:y}=s.useEditorActions();function x(R){var S,v;const b={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(v=R==null?void 0:R.to)==null?void 0:v.toISOString()};y(t.name,b)}function N(){y(t.name,null,!0),j(p)}function k(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:x,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(at,{className:"w-72",id:t.id,sortableType:n,column:t,children:k()})}function yo({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var j,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(y=>y.activeId),m={},u=c||((p=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(y){const x=s.isDateDataType(y.type);return y.id===cn.id?e.jsx(at,{id:y.id,sortableType:l,column:y,children:e.jsx(vo,{})},y.id):x?e.jsx(jo,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(fo,{droppableId:t,sortableType:l,column:y},y.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(y=>f(y))})]})})}function vo(){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 bo(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(yo,{onRemoveColumn:r,sortableType:Os,id:Rs,label:"Filters",columns:t,previewColumns:n})})}function No(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l}=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(ps,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(hn,{sql:r==null?void 0:r.sql,error:l})]}),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(Ws,{}),e.jsx(Qs,{variant:"default"})]})]})}function Co(){const t=M.useRef(null),n=M.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,m,u;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=n.current)==null||u.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(xl,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(ro,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(es,{})})]}):e.jsx(es,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(po,{})})}),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(No,{}),e.jsx(bo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(es,{})})]})})]}):e.jsx(es,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function So(t){const n=s.useAIInteractionStore(z=>z.currentAIContext),[a,r]=M.useState(""),[l,o]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.python}),{setCardPython:u,setCardSql:h,setRunSql:f,switchCardType:g,setQueryConfig:j}=s.useEditorActions(),p=s.useEditorStore(z=>z.currentAssitantScope)||[],y=s.useEditorStore(z=>z.userInputForAI),x=s.useEditorStore(z=>z.triggerAIRun),N=s.useEditorStore(z=>z.card),k=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),b=s.useEditorStore(z=>z.selectedConnectionId),S=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:E,refetch:w,data:O}=s.useDashboardCardQuery(N),{setTriggerAIRun:D,setCurrentAssitantScope:F,setCardConfig:T}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:C,selectedDatamodelId:L}=s.useEditorAside(),{messages:A,setMessages:P,reload:V,error:U,append:W,input:ee,setInput:Q,status:q,handleInputChange:H,handleSubmit:$,stop:B}=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:n},maxSteps:10,onError:z=>{console.log("on error",z)},onToolCall:_,onFinish(z,X){Y(X.usage),r(""),X.finishReason==="stop"&&r("")}});M.useEffect(()=>{x&&y&&(W({role:"user",content:y}),D(!1))},[x,y,W,D]);async function _({toolCall:z}){var X,le,ye,ve;if(["createChartFromSql","createForecast"].includes(z.toolName)){const se=z.args.sql,ce=z.args.python,de=z.args.chartType;return g(de),h(se),u(ce),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),ne(),{status:"success",tables:p};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const se=z.args.chartType,ce=z.args.queryConfig;z.args.cardConfig,g(se),T(ce),h(void 0),u(void 0);const de=await w();return(X=de==null?void 0:de.data)!=null&&X.error?{status:"error",queryConfig:ce,message:(le=de==null?void 0:de.data)==null?void 0:le.error.message}:(ye=de==null?void 0:de.data)!=null&&ye.records?{status:"success",queryConfig:ce,message:"The data has been visualized"}:{status:"success",queryConfig:ce,message:"The data has been visualized",records:(ve=de==null?void 0:de.data)==null?void 0:ve.records}}else r("Analyzing...")}}function Y(z){o(X=>X?{promptTokens:X.promptTokens+z.promptTokens,completionTokens:X.completionTokens+z.completionTokens,totalTokens:X.totalTokens+z.totalTokens}:z)}function J(z){const X=s.removeFromScopeArray(p,z);te(X)}function te(z){const X=s.sanitizeAIScope(z);F(X),P(le=>[...le,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(X)}`}])}function re(){const z={databaseName:k||"",schemaName:S||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(I),connectionId:b||"",connectionType:C||""},X=s.dedup([...p,z]);te(X)}function ne(){const z={databaseName:k||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:b||"",connectionType:C||"",datamodelId:L||""};if(!s.isInAiScopeArray([...v||[],...p],z)||p.length===0){const le=s.dedup([...v||[],...p,z]).filter(ye=>ye.connectionId===z.connectionId);te(le)}}const ue=!["ready","error"].includes(q),K=s.getErrorMessage(U);return{messages:A,setMessages:P,reload:V,append:W,input:ee,setInput:Q,isLoading:ue,handleSetAIScope:ne,handleAddCurrentTableToScope:re,removeFromCurrentSelections:J,currentAssitantScope:p,setCurrentAssitantScope:F,handleInputChange:H,handleSubmit:$,stop:B,chatStatus:q,toolStatus:a,llmUsage:l,onFinish:t,errorMessage:K}}const wo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Dt(){const t=M.useRef(null),n=M.useRef(null),[a,r]=M.useState(!1),[l,o]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,m]=M.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),f=s.useDashboardStore(B=>B.dashboard.aiContext),g=s.useEditorStore(B=>B.card.dataSource),j=s.useEditorStore(B=>B.actions.setCardSql),p=s.useEditorStore(B=>B.actions.setRunSql),y=s.useEditorStore(B=>B.showAIDialog),x=s.useDashboardStore(B=>B.handleOpenAssistantProfile),{setShowAIDialog:N,setCardPython:k}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:b}=s.useAssistantProfile(),{messages:S,setMessages:v,reload:E,append:w,input:O,setInput:D,isLoading:F,handleInputChange:T,handleSubmit:I,stop:C,chatStatus:L,llmUsage:A,errorMessage:P}=So();s.useAssistantScroll({scrollContainerRef:t,inputRef:n,messages:S}),M.useEffect(()=>{var B;y&&((B=n.current)==null||B.focus(),h({selectedEntities:(g==null?void 0:g.selectedEntities)||[]}))},[y,g,h]);function V(B,_){_==="sql"?(j(B),p(!0)):_==="python"&&(k(B),p(!0))}function U(){var B;(B=f==null?void 0:f.selectedEntities)==null||B[0],m(!0)}function W(){u.selectedEntities.length===0&&h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function ee(B){W();const _={role:"user",content:B.title+" "+B.subtitle};w(_)}function Q(B){W(),w({role:"user",content:B})}function q(){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:a,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function H(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(O==null?void 0:O.length)===0&&(S==null?void 0:S.filter(B=>B.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:[H(),x&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:x,children:(b==null?void 0:b.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:U,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:()=>{v([]),E()},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:()=>{N(!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:l,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:L,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[$&&!b&&e.jsx(s.Placeholders,{onClick:ee,placeholders:wo}),e.jsx("div",{children:$&&b&&e.jsx(s.SeedQuestions,{seedQuestions:b.seedQuestions||[],handleSeedQuestionClick:Q})})]}),e.jsx(s.ChatInputWithContext,{ref:n,setInput:D,stop:C,input:O,handleInputChange:T,handleSubmit:B=>{W(),I(B)},isLoading:F,onFocus:()=>{}}),A&&a&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",A.promptTokens," prompt tokens,"," ",A.completionTokens," completion tokens,"," ",A.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(g==null?void 0:g.selectedEntities)||[],open:d,onOpenChange:m,dataSource:g||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const rt=t=>{var D;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(F=>F.card.type),h=t==null?void 0:t.id,f=M.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){case"groupBy":return(t.config.groupByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,dateFormat:T.dateFormat,customFormat:T.customFormat,granularity:T.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,direction:T.direction}));case"source":return[];default:return[]}},[t]),g=M.useCallback((F,T)=>{if(h)switch(F){case"groupBy":{n(h,{groupByColumns:T});break}case"metrics":{n(h,{metricColumns:T});break}case"pivotBy":{n(h,{pivotByColumns:T});break}case"sortBy":{n(h,{sortByColumns:T});break}}},[h,n]),j=M.useCallback((F,T,I)=>{if(!h)return;const L=f(F)[T];if(L)switch(F){case"groupBy":a(h,L.id,{label:I});break;case"metrics":r(h,L.id,{label:I});break;case"pivotBy":l(h,L.id,{label:I});break;case"sortBy":o(h,L.id,{label:I});break}},[h,f,a,r,l,o]),p=M.useCallback((F,T)=>{if(!h)return;const C=f("metrics")[F];C&&r(h,C.id,{aggregate:T,label:s.getAggregationLabel(C.name,T)})},[h,f,r]),y=M.useCallback((F,T,I)=>{if(!h)return;const L=f("groupBy")[F];if(!L)return;const A={dateFormat:T};T==="custom"&&I?A.customFormat=I:A.customFormat=void 0,a(h,L.id,A)},[h,f,a]),x=M.useCallback((F,T)=>{if(!h)return;const C=f("groupBy")[F];C&&a(h,C.id,{granularity:T})},[h,f,a]),N=M.useCallback((F,T)=>{if(!h)return;const C=f("metrics")[F];C&&r(h,C.id,{aliasTemplate:T})},[h,f,r]),k=M.useCallback((F,T)=>{if(console.log("handleValueAliasesChange",F,T),!h)return;console.log("handleValueAliasesChange",F,T);const C=f("metrics")[F];C&&(console.log("handleValueAliasesChange",T),r(h,C.id,{valueAliases:T}))},[h,f,r]),R=M.useCallback(F=>{h&&n(h,{comparisonType:F})},[h,n]),b=M.useCallback(F=>{h&&n(h,{showTrendline:F})},[h,n]),S=M.useCallback(F=>{h&&n(h,{trendlineWindow:F})},[h,n]),v=M.useCallback(F=>{h&&n(h,{trendlineGranularity:F})},[h,n]),E=M.useCallback(F=>{h&&n(h,{targetValue:F})},[h,n]),w=M.useCallback(F=>{var V;if(!h)return;const T=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,C=s.validateEntityConsistency(F,T,I);if(!C.isValid){C.showError&&s.showJoinRequiredNotification();return}const L=s.getSmartContainerForField(F,T),A=f(L);if(s.fieldAlreadyExists(F,A))return;const P=s.getNewField(F,L,A);P&&g(L,[...A,P])},[h,(D=t==null?void 0:t.config)==null?void 0:D.joinPlan,f,g]),O=M.useCallback((F,T)=>{if(!h)return;const C=f(F)[T];if(C){if(F!=="sortBy"){const L=f("sortBy"),A=L.filter(P=>!(P.name===C.name&&P.qualifiedEntityName===C.qualifiedEntityName));A.length!==L.length&&n(h,{sortByColumns:A})}switch(F){case"groupBy":c(h,C.id);break;case"metrics":i(h,C.id);break;case"pivotBy":d(h,C.id);break;case"sortBy":m(h,C.id);break}}},[h,f,c,i,d,m,n]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:x,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:O,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:b,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:E,cardType:u}};function ko({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 Do({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),m=s.useEditorStore(j=>j.card),{handleFieldClick:u}=rt(m),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=j=>{const p=(j||"").toLowerCase();switch(s.getDataType(p)){case"number":return Fe;case"date":return s.Calendar;case"boolean":return Je;case"json":return Es;case"geo":return Is;default:return Be}},g=j=>{const p=(j||"").toLowerCase(),y=s.getDataType(p);return y==="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(Be,{className:"h-3 w-3"})}):y==="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(Fe,{className:"h-3 w-3"})}):y==="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"})}):y==="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(Je,{className:"h-3 w-3"})}):y==="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(Es,{className:"h-3 w-3"})}):y==="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(Is,{className:"h-3 w-3"})}):y==="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(Fs,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[g(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(ko,{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(Vt,{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(Ha,{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 To(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useEditorStore(k=>k.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const R=s.getDataType(k.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(a==="all"?m:m.filter(k=>u(k)===a)).reduce((k,R)=>{const b=R.qualifiedEntityName||"Other Fields";return k[b]||(k[b]={label:s.toLabel(R.entityName),fields:[]}),k[b].fields.push(R),k},{}),j=Object.keys(f),p=m.filter(k=>u(k)==="dimensions").length,y=m.filter(k=>u(k)==="metrics").length,x=m.filter(k=>u(k)==="calculated").length,N=m.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):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"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>n(k.target.value)})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:k=>r(k),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:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Fs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(f).map(([k,R])=>{const b=c.find(S=>S.entityName===k)||{entityName:k,label:R.label};return e.jsxs(s.AccordionItem,{value:k,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:b.label||b.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(Do,{field:S},S.id))})})]},k)})}),Object.keys(f).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function Eo(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(To,{})," "]})}function Io({initialJoinPlan:t,availableDataSources:n}){const[a,r]=M.useState(t),[l,o]=M.useState(new Set),c=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(E=>E.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=S=>{r({...a,joins:a.joins.filter(v=>v.id!==S)}),o(new Set([...l].filter(v=>v!==S)))},d=(S,v)=>{var D,F;const E=a.joins.find(T=>T.id===S);if(!E)return;const w={...E,...v},O=a.joins.map(T=>T.id===S?w:T);if((D=w.source)!=null&&D.name&&((F=w.target)!=null&&F.name)&&w.joinKeyGroups[0].keys.length===0){const T=n.find(A=>{var P;return A.name===((P=w.source)==null?void 0:P.name)}),I=n.find(A=>{var P;return A.name===((P=w.target)==null?void 0:P.name)}),C={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},L=[...w.joinKeyGroups];L[0]={...L[0],keys:[C]},w.joinKeyGroups=L,O[O.findIndex(A=>A.id===S)]=w}r({...a,joins:O})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const v=a.joins.findIndex(E=>E.id===S);if(v>0){const E=[...a.joins],w={...E[v]},O={...E[v-1]};E[v]=O,E[v-1]=w,E.forEach((F,T)=>{F.sequence=T+1});const D={...a,joins:E};r(D)}},moveJoinDown:S=>{const v=a.joins.findIndex(E=>E.id===S);if(v<a.joins.length-1){const E=[...a.joins],w={...E[v]},O={...E[v+1]};E[v]=O,E[v+1]=w,E.forEach((F,T)=>{F.sequence=T+1});const D={...a,joins:E};r(D)}},toggleJoinExpansion:S=>{const v=new Set(l);v.has(S)?v.delete(S):v.add(S),o(v)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(w=>w.id===S);if(v===0)return n;const E=new Set;return a.baseEntity.name&&E.add(a.baseEntity.name),a.joins.slice(0,v).forEach(w=>{E.add(w.source.name),E.add(w.target.name)}),n.filter(w=>E.has(w.name))},getAvailableTargetEntities:S=>n.filter(v=>v.name!==S),addJoinKeyGroup:S=>{const v=a.joins.find(w=>w.id===S);if(!v)return;const E=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:E})},updateGroupOperator:(S,v,E)=>{const w=a.joins.find(D=>D.id===S);if(!w)return;const O=[...w.joinKeyGroups];O[v]={...O[v],operator:E},d(S,{joinKeyGroups:O})},removeJoinKeyGroup:(S,v)=>{const E=a.joins.find(O=>O.id===S);if(!E)return;const w=[...E.joinKeyGroups];w.splice(v,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,v)=>{const E=a.joins.find(T=>T.id===S);if(!E)return;const w=n.find(T=>T.name===E.source.name),O=n.find(T=>T.name===E.target.name),D=[...E.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};D[v]={...D[v],keys:[...D[v].keys,F]},d(S,{joinKeyGroups:D})},updateJoinKey:(S,v,E,w,O)=>{const D=a.joins.find(L=>L.id===S);if(!D)return;const F=n.find(L=>L.name===D.source.name),T=n.find(L=>L.name===D.target.name),I=[...D.joinKeyGroups],C=I[v].keys[E];w==="sourceColumnName"&&F?I[v].keys[E]={...C,source:{...C.source,name:O}}:w==="targetColumnName"&&T?I[v].keys[E]={...C,target:{...C.target,name:O}}:w==="operator"&&(I[v].keys[E]={...C,operator:O}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,v,E)=>{const w=a.joins.find(D=>D.id===S);if(!w)return;const O=[...w.joinKeyGroups];O[v].keys.splice(E,1),d(S,{joinKeyGroups:O})},generateSQLPreview:()=>{const S=[...a.joins].sort((w,O)=>w.sequence-O.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
420
+ FROM ${v.name}`;return S.forEach(w=>{const O=n.find(T=>T.name===w.target.name);if(!O)return;const D=w.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const I=T.keys.filter(C=>{var L,A,P,V;return((L=C.source)==null?void 0:L.name)&&((A=C.target)==null?void 0:A.name)&&((P=C.source)==null?void 0:P.entityName)&&((V=C.target)==null?void 0:V.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return I.length>1?`(${I.join(` ${T.operator} `)})`:I[0]}).filter(Boolean),F=D.length>1?D.join(" OR "):D[0]||"condition_here";E+=`
421
+ ${w.joinType} JOIN ${O.name}
422
+ ON ${F}`}),E},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(w=>!w.source.name||!w.target.name)||a.joins.some(w=>w.joinKeyGroups.some(O=>O.keys.length===0))||a.joins.some(w=>w.joinKeyGroups.some(O=>O.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function Ao({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:p,getAvailableSourceEntities:y,getAvailableTargetEntities:x,addJoinKeyGroup:N,updateGroupOperator:k,removeJoinKeyGroup:R,addJoinKey:b,updateJoinKey:S,removeJoinKey:v,generateSQLPreview:E,isValidConfiguration:w}=Io({initialJoinPlan:t,availableDataSources:n}),O=D=>{const F=c.find(T=>T.entityName===D);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:D=>{const F=n.find(T=>T.name===D);m({...i,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:D,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(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:E()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:u,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 F=n.find(C=>C.name===D.source.name),T=n.find(C=>C.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,F&&T&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",T.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(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:()=>j(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:()=>p(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:C=>{const L=n.find(A=>A.name===C);f(D.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:C,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(D.id).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name]})},C.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:C=>f(D.id,{joinType:C}),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:C=>{const L=n.find(A=>A.name===C);f(D.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:C,database:L==null?void 0:L.database,schema:L==null?void 0:L.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?x(D.source.name).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,C.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},C.name)):[]})]})]})]}),D.source.name&&D.target.name&&F&&T&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>N(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((C,L)=>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 ",L+1]}),L>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:C.operator,onValueChange:A=>k(D.id,L,A),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,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[C.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:C.keys.map((A,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:C.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:A.source.name,onValueChange:V=>S(D.id,L,P,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:O(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:A.operator,onValueChange:V=>S(D.id,L,P,"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:A.target.name,onValueChange:V=>S(D.id,L,P,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:O(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:()=>v(D.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},A.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>b(D.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},C.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(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!w(),children:"Save"})]})]})}function Tt({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ao,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Mo({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(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((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Lo(){var u,h;const t=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.actions.updateCardConfig),a=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{n(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const f=[...a.joins].sort((p,y)=>p.sequence-y.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
423
+ FROM ${g.name}`;return f.forEach(p=>{const y=o.find(k=>k.name===p.target.name);if(!y)return;const x=p.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const R=k.keys.filter(b=>{var S,v,E,w;return((S=b.source)==null?void 0:S.name)&&((v=b.target)==null?void 0:v.name)&&((E=b.source)==null?void 0:E.entityName)&&((w=b.target)==null?void 0:w.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return R.length>1?`(${R.join(` ${k.operator} `)})`:R[0]}).filter(Boolean),N=x.length>1?x.join(" OR "):x[0]||"condition_here";j+=`
424
424
  ${p.joinType} JOIN ${y.name}
425
- ON ${b}`}),j};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$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:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Mo,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(Tt,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Tt,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Ro({open:t,onOpenChange:n}){const[a,r]=M.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];M.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(y=>y.some(b=>b.name===p.name&&b.type===p.type)?y.filter(b=>!(b.name===p.name&&b.type===p.type)):[...y,p])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(a.length===0)return;const p=a[0],y=p.connectionId||"",x=p.connectionType||"",w=a.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:x,mode:w,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ka,{className:"h-4 w-4"});case"model":return e.jsx(pa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const y=[];return p.database&&y.push(p.database),p.schema&&y.push(p.schema),p.name&&y.push(p.name),y.join(".")},j=p=>a.some(y=>y.name===p.name&&y.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Oo({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,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 Bo({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Fo({isVisible:t,onToggleVisibility:n}){const[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(f=>f.card.dataSource);we();const{updateDataSource:m}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...u,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:n,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:j=>{j.stopPropagation();const p=h.selectedEntities.filter(y=>!(y.name===f.name&&y.type===f.type));m({...u,...d,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(Oo,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(Bo,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(Lo,{})]})]}),e.jsx(Eo,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:u}),e.jsx(Ro,{open:l,onOpenChange:o})]})}const rs=[{id:"table",icon:Ye,label:"Table"},{id:"pivotTable",icon:Ye,label:"Pivot Table"},{id:"aggregateTable",icon:Ye,label:"Aggregate Table"},{id:"bar",icon:ms,label:"Bar Chart"},{id:"line",icon:hs,label:"Line Chart"},{id:"area",icon:Rt,label:"Area Chart"},{id:"stackedBar",icon:Fs,label:"Stacked Bar Chart"},{id:"combo",icon:da,label:"Combo Chart"},{id:"stackedLine",icon:et,label:"Stacked Line Chart"},{id:"scatter",icon:zs,label:"Scatter Chart"},{id:"bubble",icon:Xs,label:"Bubble Chart"},{id:"pie",icon:xs,label:"Pie Chart"},{id:"doughnut",icon:Vs,label:"Doughnut Chart"},{id:"funnel",icon:Zs,label:"Funnel Chart"},{id:"radar",icon:Us,label:"Radar Chart"},{id:"polarArea",icon:Js,label:"Polar Area Chart"},{id:"tornado",icon:$s,label:"Tornado Chart"},{id:"range",icon:Ps,label:"Range Chart"},{id:"kpi",icon:st,label:"KPI"},{id:"text",icon:Lt,label:"Text"},{id:"map",icon:_s,label:"Map"}],lt=t=>{const n=t.toLowerCase();for(const a of rs)if(a.id==="doughnut"){if(n.includes("doughnut")||n.includes("donut")){const r=a.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(n.includes(a.id.toLowerCase())){const r=a.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},Po="chart-selector-standard-first";function zo(){const[t,n]=s.useLocalStorageState(Po,!0);return{standardFirst:t,updatePreference:n}}const Et=({pluginVisual:t,index:n,onSelect:a})=>{const r=fs(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=lt(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},It=["default","standardPlugin","customPlugin"];function Vo({selectedChart:t,onChartChange:n}){var R;const[a,r]=M.useState(!1),{data:l}=yn();zo();const c=((R=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:R.url)||"";Ys(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:m}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:u,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),p=M.useMemo(()=>g?[g,...It.filter(N=>N!==g)]:It,[g]);function y(N){u(null),d({}),i(N),["custom","text","map"].includes(N)&&(m(!0),f(void 0)),n(N),r(!1)}function x(N){u(null),d({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),f(void 0),n("custom"),r(!1)}const b=()=>{var S;if(t==="custom"){const v=s.useEditorStore.getState().card;return((S=v==null?void 0:v.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const N=rs.find(v=>v.id===t);return(N==null?void 0:N.label)||"Select chart type"},w=()=>{var S,v;if(t==="custom"){const k=s.useEditorStore.getState().card,T=(S=k==null?void 0:k.customCardPreferences)==null?void 0:S.icon,O=(v=k==null?void 0:k.customCardPreferences)==null?void 0:v.componentName;if(T&&O)return e.jsx(_o,{icon:T,componentName:O});if(O){const D=lt(O);if(D)return D}return e.jsx(Qe,{className:"h-4 w-4"})}const N=rs.find(k=>k.id===t);if(N){const k=N.icon;return e.jsx(k,{className:"h-4 w-4"})}return e.jsx(Qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[w(),e.jsx("span",{children:b()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.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:g==="default",onCheckedChange:S=>j(S?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:rs.map(S=>{const v=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>y(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(N==="standardPlugin"){const S=l.filter(v=>v.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>j(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(v=>v.componentType==="chart").map((v,k)=>e.jsx(Et,{pluginVisual:v,index:k,onSelect:()=>x(v)},`${v.url}-${v.name}-${k}`))},"standardPlugin"):null}if(N==="customPlugin"){const S=l.filter(v=>v.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>j(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((v,k)=>e.jsx(Et,{pluginVisual:v,index:k,onSelect:()=>x(v)},`${v.url}-${v.name}-${k}`))},"customPlugin"):null}return null})]})]})})]})})}const _o=({icon:t,componentName:n})=>{const a=fs(),r=lt(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Qe,{className:"h-4 w-4"})},ot=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Fe,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Je,{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(Fe,{className:"h-3 w-3"})})};function Uo({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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:l?a:t,onChange:m=>{r(m.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&a!==t?(n(a),o(!1)):m.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function $o({valueAliases:t,onValueAliasesChange:n}){const[a,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{n({...t,"":""})},m=h=>{const f={...t};delete f[h],n(f)},u=h=>{const f={...t};delete f[h],f[l]=c,n(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],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(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),o(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:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function qo({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(d=>d.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:o.connectionId,cardConfig:d,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",m);const u=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",m);if(u!=null&&u.error)return console.error("Error fetching attribute values:",u.error),[];const h=t.name;return((u==null?void 0:u.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Yo({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var w,R;const c=!!l,[i,d]=M.useState(c?"values":"fields"),[m,u]=M.useState(""),[h,f]=M.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(N=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(k=>k.field.id===N.id))&&N.label.toLowerCase().includes(m.toLowerCase())}),j=N=>{f({...h,field:N}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const v=((r==null?void 0:r.conditions)||[]).map(k=>k.id===l.id?N:k);S={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,N],groups:[]}}o(S),n(!1)}},y=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(N.length>0){const S={...r,conditions:N};o(S)}else o(void 0);n(!1)},x=N=>{f({...h,selectedValues:N})},b=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(f({id:s.v4(),field:null,selectedValues:[]}),d("fields")),u("")};return M.useEffect(()=>{t&&b()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(w=h.field)==null?void 0:w.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:m,onChange:N=>u(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(N),children:[e.jsx(ot,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),g.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),g.length===0&&!m&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Go,{field:h.field,selectedValues:h.selectedValues,onValuesChange:x,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:b,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Go({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=M.useState(""),{values:c,isLoading:i,isFetching:d}=qo({field:t,searchQuery:l,limit:500}),m=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,u=f=>{const g=n.includes(f);a(g?n.filter(j=>j!==f):[...n,f])},h=()=>{n.length===m.length&&m.length>0?a([]):a(m.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===m.length&&m.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>u(f.value),children:[e.jsx(s.Checkbox,{checked:n.includes(f.value),onCheckedChange:()=>u(f.value)}),e.jsx(gs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function Ho({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var dt,ut,mt;const{attributes:i,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:j,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:x,handleAliasTemplateChange:b,handleValueAliasesChange:w,removeField:R,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:T}=rt(g),[O,D]=M.useState(!1),[B,E]=M.useState(!1),[I,C]=M.useState(null),[L,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[P,V]=M.useState(t.customFormat||""),[U,W]=M.useState(!!t.customFormat),[ee,Q]=M.useState(t.granularity||"day"),[q,H]=M.useState(t.aliasTemplate||""),[$,F]=M.useState(t.valueAliases||{}),[_,Y]=M.useState((dt=t.parameters)==null?void 0:dt.filters),J=G=>{G==="custom"?W(!0):(W(!1),A(G),n==="groupBy"&&y(a,G,""))},te=G=>{V(G),n==="groupBy"&&y(a,"custom",G)},re=G=>{var me;Q(G);const ie=(me=ce(G)[0])==null?void 0:me.value;ie&&!U&&(A(ie),n==="groupBy"&&y(a,ie,"")),n==="groupBy"&&x(a,G)},ne=G=>{H(G),n==="metrics"&&b(a,G)},ue=G=>{F(G),n==="metrics"&&w(a,G)},K=G=>{j(n,a,G)},z=G=>{var oe;if(Y(G),n==="metrics"){const ie={...t,parameters:{...t.parameters,filters:G}},me=[...((oe=g.config)==null?void 0:oe.metricColumns)||[]];me[a]=ie,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:me})}E(!1)},X=()=>{R(n,a)},le={transform:s.CSS.Transform.toString(u),transition:h},ye=s.getDataType(t.dataType),ve=ye==="date",se=c==="kpi",ce=G=>{switch(G){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..."}]}},de=ce(ee),Pn=n!=="pivotBy",zn=ve&&n==="groupBy",Vn=!se&&ve&&n==="groupBy",_n=se&&ve&&n==="groupBy",Un=se&&n==="metrics"&&((ut=g.config)==null?void 0:ut.comparisonType)==="target",$n=n==="metrics",qn=()=>e.jsx("div",{onPointerDown:G=>{G.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Yn=()=>Pn?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:K,placeholder:"Display label...",type:"text"})]}):null,ct=()=>zn?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:ee,onValueChange:re,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,Gn=()=>Vn?e.jsxs(e.Fragment,{children:[ct(),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:U?"custom":L,onValueChange:J,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:de.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),U&&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:P,onChange:G=>{G.stopPropagation(),te(G.target.value)},onClick:G=>G.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,Hn=()=>{var G,oe,ie,me,ke;return _n?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:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:N,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:((oe=g.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:S})]})}),((ie=g.config)==null?void 0:ie.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:((me=g.config)==null?void 0:me.trendlineWindow)||30,onChange:Ze=>{const Xn=parseInt(Ze.target.value)||30;v(Xn)},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:((ke=g.config)==null?void 0:ke.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},Kn=()=>{var G,oe;return Un?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(Ne,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((oe=g.config)==null?void 0:oe.targetValue)!==null?String(g.config.targetValue):"",onSave:ie=>{!isNaN(Number(ie))&&ie!==null?T(Number(ie)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},Qn=()=>$n?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:G=>{p(a,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{C(G),E(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((oe,ie)=>e.jsx("div",{children:String(oe)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var me;oe.stopPropagation();const ie=_.conditions.filter(ke=>ke.id!==G.id);if(ie.length>0){const ke={..._,conditions:ie};z(ke)}else if(Y(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Ze=[...((me=g.config)==null?void 0:me.metricColumns)||[]];Ze[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ze})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{C(null),E(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Rn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Uo,{aliasTemplate:q,onAliasTemplateChange:ne}),e.jsx($o,{valueAliases:$,onValueAliasesChange:ue})]})]}):null,{columns:Wn=[]}=s.useColumns(),Jn=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:m,style:le,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ot,{dataType:ye}),e.jsx(gs,{className:s.cn("w-[140px] flex-1 text-sm",Jn&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((mt=_==null?void 0:_.conditions)==null?void 0:mt.length)&&!O&&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-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),D(!O)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${O?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const oe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",oe),l(oe)},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:G=>{G.stopPropagation(),X()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[qn(),Yn(),c==="kpi"&&ct(),Gn(),Hn(),Kn(),Qn()]})]}),B&&e.jsx(Yo,{open:B,onOpenChange:G=>{E(G),G||C(null)},availableFields:Wn,existingFilters:_,editingCondition:I,onSave:G=>{var oe;if(G)z(G);else if(Y(void 0),n==="metrics"){const ie={...t,parameters:{...t.parameters,filters:void 0}},me=[...((oe=g.config)==null?void 0:oe.metricColumns)||[]];me[a]=ie,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:me})}C(null)}})]})}function Ko({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$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:n()})]})})}function ts({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(j=>j.card),u=s.useEditorStore(j=>j.card.type),h=n.length>0,f=(j,p)=>{var x;!((x=m.config)!=null&&x.sortByColumns)||m.config.sortByColumns.findIndex(b=>b.id===j)===-1||d(m.id,j,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Ko,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 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:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map((j,p)=>{const x=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Ho,{field:j,zone:t,index:p,sortDirection:x,onSortDirectionChange:b=>f(j.id,b),hasPivotColumns:o,cardType:u})})},j.id)})})})})]})}const At=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Qo=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ds({value:t,onChange:n,label:a}){const[r,l]=M.useState(!1),[o,c]=M.useState(!1),i=()=>{const d=At.find(m=>m.value===t);return d?d.color:t.startsWith("#")?t:At[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Qo.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Tn,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ns={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
426
- Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Wo(){var i,d,m,u,h,f,g,j,p,y;const t=s.useEditorStore(x=>x.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((u=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:u.metricComparison)||{},c=x=>{var w;const b={...t.preferences,kpiVisualOptions:{...(w=t.preferences)==null?void 0:w.kpiVisualOptions,metricComparison:{...o,...x}}};n(b)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ns).map(([x,b])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:b.label},x))})]}),(()=>{var b,w,R;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(b=ns[x])==null?void 0:b.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(w=ns[x])==null?void 0:w.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=ns[x])==null?void 0:R.example]})]})})()]}),e.jsx(nt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ds,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(Ds,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(Ds,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Jo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(nt,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Xo({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(j=>{var p;return((p=j.card.customCardPreferences)==null?void 0:p.url)&&j.card.type==="custom"}),o=s.useEditorStore(j=>j.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",m=c!=="kpi"&&i,u=["pie","doughnut","polar","funnel"].includes(c),h=d&&!u,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Aa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ts,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(ts,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ts,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),m&&e.jsx(ts,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Jo,{}),e.jsx(Wo,{}),e.jsx(En,{}),e.jsx(In,{}),e.jsx(An,{}),e.jsx(Mn,{})]})})]})]})}function Zo({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(Vo,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||u}),children:e.jsx(ps,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Xo,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function ei({initialFilters:t,availableFields:n}={}){const[a,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=N=>{const S=v=>{if(v.id===N){const k=i[0]||d;return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},u=N=>{const S=v=>{if(v.id===N){const k=i[0]||d;return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},h=(N,S)=>{const v=k=>k.id===N?{...k,conditions:k.conditions.filter(T=>T.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},f=(N,S)=>{const v=k=>k.id===N?{...k,groups:k.groups.filter(T=>T.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(N,S,v,k)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=O=>O.id===N?{...O,conditions:O.conditions.map(D=>D.id===S?{...D,[v]:k}:D)}:{...O,groups:O.groups.map(T)};r(T(a))},j=(N,S,v)=>{const k=T=>T.id===N?{...T,conditions:T.conditions.map(O=>O.id===S?{...O,...v}:O)}:{...T,groups:T.groups.map(k)};r(k(a))},p=(N,S)=>{const v=k=>k.id===N?{...k,logicalOperator:S}:{...k,groups:k.groups.map(v)};r(v(a))},y=(N,S)=>{const v=k=>k.id===N?{...k,negate:S}:{...k,groups:k.groups.map(v)};r(v(a))},x=(N,S,v)=>{const k=T=>T.id===N?{...T,conditions:s.arrayMove(T.conditions,S,v)}:{...T,groups:T.groups.map(k)};r(k(a))},b=(N,S,v)=>{const k=T=>T.id===N?{...T,groups:s.arrayMove(T.groups,S,v)}:{...T,groups:T.groups.map(k)};r(k(a))},w=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const S=k=>{let T="";typeof k.field=="object"?T=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:T=String(k.field);const O=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 B=[];Array.isArray(D)?B=D.map(E=>typeof E=="string"?`'${E}'`:String(E)):typeof D=="string"?B=D.split(",").map(E=>{const I=E.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(B=[String(D)]),D=`(${B.join(", ")})`}switch(O){case"contains":return typeof D=="string"?`${T} LIKE '%${D.replace(/'/g,"")}'`:`${T} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${T} LIKE '${D.replace(/'/g,"")}%'`:`${T} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${T} LIKE '%${D.replace(/'/g,"")}'`:`${T} LIKE '%${String(D)}'`;default:return`${T} ${O} ${D}`}},v=k=>{const T=k.conditions.map(S),O=k.groups.map(I=>v(I)),D=[...T,...O].filter(Boolean);if(D.length===0)return"";const B=D.join(` ${k.logicalOperator} `),E=D.length>1?`(${B})`:B;return k.negate?`NOT ${E}`:E};return v(N)},R=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:u,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:j,updateGroupOperator:p,updateGroupNegate:y,reorderConditions:x,reorderGroups:b,generateSQLPreview:w,hasAnyFilters:R}}function si({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const ti=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(ya,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},ni=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ai({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return a.forEach(m=>{const u=ni(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][m.entityId].push(m)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(si,{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,m])=>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(m).map(([u,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:[ti(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{n(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+g))]},`${d}-${u}`))},d))})]})})]})}function it(t){var j;const n=s.useEditorStore(p=>p.card),{authToken:a}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},m=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:u,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",(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:n.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(p=>({label:p[t.name]||"BLANK",value:p[t.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function ri({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=xe.useState(!1),{filterValues:i}=it(t),d=u=>{a(n.filter(h=>h!==u))},m=u=>{n.includes(u)?a(n.filter(h=>h!==u)):a([...n,u])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(u=>{const h=i.find(f=>f.value===u);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(u)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):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((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const Bn=t=>{if(!t)return 0;let n=t.conditions.length;return t.groups.forEach(a=>{n+=Bn(a)}),n};function li({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=it(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const oi=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],ii=["=","!=","contains","startsWith","endsWith","in","not in"],ci=["=","!=",">",">=","<","<=","in","not in"],di=["=","!="],ui=["=","!=",">",">=","<","<=","in","not in"];function mi(t){switch(t){case"string":return ii;case"number":return ci;case"boolean":return di;case"date":return ui;default:return oi}}function Fn({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:u,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:p,error:y}=it(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...u,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(a,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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(ai,{value:t.field,onValueChange:b=>{d(a,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(a,t.id,{operator:b,value:[]}):d(a,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:mi(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"?p?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ri,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(a,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(a,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(li,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(a,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(a,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=>l(a,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:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function hi({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:j,updateConditionFields:p}){const{attributes:y,listeners:x,setNodeRef:b,transform:w,transition:R,isDragging:N}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(w),transition:R},v=T=>{const{active:O,over:D}=T;if(D&&O.id!==D.id){const B=t.conditions.findIndex(I=>I.id===O.id),E=t.conditions.findIndex(I=>I.id===D.id);B!==-1&&E!==-1&&m(t.id,B,E)}},k=T=>{const{active:O,over:D}=T;if(D&&O.id!==D.id&&a){const B=t.groups.findIndex(I=>I.id===O.id),E=t.groups.findIndex(I=>I.id===D.id);B!==-1&&E!==-1&&u(a,B,E)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...y,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:T=>r(t.id,T),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((T,O)=>e.jsx(Fn,{condition:T,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},T.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(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(T=>j(T,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function xi({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:u,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:p,reorderConditions:y,reorderGroups:x,generateSQLPreview:b,hasAnyFilters:w,setCurrentFilters:R}=ei({initialFilters:t,availableFields:n}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,v]=M.useState(!1),k=(D,B,E)=>{const I=C=>C.id===D?{...C,conditions:C.conditions.map(L=>L.id===B?{...L,field:E,dataType:E.dataType}:L)}:{...C,groups:C.groups.map(I)};R(I(o))},T=(D,B=0,E)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:C,over:L}=I;if(L&&C.id!==L.id){const A=D.conditions.findIndex(V=>V.id===C.id),P=D.conditions.findIndex(V=>V.id===L.id);A!==-1&&P!==-1&&y(D.id,A,P)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,C)=>e.jsx(Fn,{condition:I,index:C,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:u,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},I.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:C,over:L}=I;if(L&&C.id!==L.id){const A=D.groups.findIndex(V=>V.id===C.id),P=D.groups.findIndex(V=>V.id===L.id);A!==-1&&P!==-1&&x(D.id,A,P)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>T(I,B+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:()=>m(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(hi,{group:D,depth:B,parentGroupId:E,onUpdateGroupOperator:j,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:u,onReorderConditions:y,onReorderGroups:x,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:T,updateConditionFields:g},D.id),O=Bn(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..."})]}):T(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>v(!!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)"})]})}),w&&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(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(w?o:null),children:"Apply Filters"})]})]})}function pi({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=m=>{a(t,m),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.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(xi,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function fi({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=M.useState(null),c=s.useEditorStore(j=>j.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],m=M.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(p=>p.id===j)?"source":a("groupBy").find(p=>p.id===j)?"groupBy":a("metrics").find(p=>p.id===j)?"metrics":a("pivotBy").find(p=>p.id===j)?"pivotBy":a("sortBy").find(p=>p.id===j)?"sortBy":null,[n,a]),u=M.useCallback(j=>{o(j.active.id)},[]),h=M.useCallback(j=>{const{active:p,over:y}=j;if(!y||!t){o(null);return}const x=p.id,b=y.id,w=m(x),R=m(b)||b;if(w==="source"&&R==="sortBy"){o(null);return}if(w==="source"&&R!=="source"&&R!=="sortBy"){const N=[...n].find(T=>T.id===x);if(!N){o(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const T=S[0].qualifiedEntityName;if(!T){o(null);return}if(T!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(T,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(R);if(s.fieldAlreadyExists(N,v)){o(null);return}const k=s.getNewField(N,R,v);o(null),r(R,[...v,k]);return}if(w&&R&&w!=="source"&&R!=="source"&&w!==R){const N=a(w),S=a(R),v=N.find(O=>O.id===x);if(!v){o(null);return}const k=s.getNewField(v,R,S);if(o(null),R==="sortBy"){if(w==="pivotBy"){o(null);return}s.fieldAlreadyExists(v,S)||r(R,[...S,k]);return}const T=N.filter(O=>O.id!==x);r(w,T),r(R,[...S,k]);return}if(w&&R&&w===R&&w!=="source"){const N=a(w),S=N.findIndex(k=>k.id===x),v=N.findIndex(k=>k.id===b);if(S!==v){const k=s.arrayMove(N,S,v);r(w,k)}}o(null)},[t,n,a,r,m,i]),f=l?d.find(j=>j.id===l):null;return{activeId:l,activeField:f,handleDragStart:u,handleDragEnd:h}}function gi({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=we();r==null||r.role;const[l,o]=M.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:m}=M.useContext(s.SemaphorContext).tokenProps,u=(m==null?void 0:m.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),j=s.useManagementStore(x=>x.selectedVisual),p=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!u&&"justify-end"),children:[u&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx(Ws,{}),a&&!p&&e.jsx(Qs,{variant:"default"}),p&&e.jsx(hl,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function ji({activeView:t,onViewChange:n}){const a=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-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"}),a.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const yi=[{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,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=M.useState(!1),[l,o]=M.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),n(t.id,parseInt(u))},i=u=>{const h=u.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:yi.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function bi({isOpen:t,onClose:n}){const a=Xt(n,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(u=>u.card),o=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:m&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ni({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:u,columnsLoading:h,columnsError:f}){var L;const g=s.useEditorStore(A=>A.card);s.useEditorStore(A=>A.frame);const j=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:p,setCard:y,updateCardInFrame:x}=s.useEditorActions(),b=s.useEditorStore(A=>A.showAIDialog),[w,R]=M.useState(!1),N=s.useEditorStore(A=>{var P;return((P=A.card.customCardPreferences)==null?void 0:P.url)&&A.card.type==="custom"}),{data:S,errorMessage:v,isPending:k,isLoading:T,isFetching:O,pagination:D}=s.useDashboardCardQuery(m),B=(A,P)=>{const V={...m,paginationConfig:{page:A+1,pageSize:P}};y(V),x(V)};function E(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(j||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.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(u.slice(0,5),null,2)})]})]})})}const I=A=>{if(!g.config)return;if(!A.length){p(g.id,{...g.config,sortByColumns:[]});return}const P=g.config,V=A.map(({id:U,desc:W})=>{var H,$;const ee=(H=P.metricColumns)==null?void 0:H.find(F=>F.label===U),Q=($=P.groupByColumns)==null?void 0:$.find(F=>F.label===U),q=ee||Q;return q?{id:s.getFieldId("sortBy",q),name:q.name,dataType:q.dataType,label:q.label,qualifiedEntityName:q.qualifiedEntityName,entityId:q.entityId,entityName:q.entityName,entityType:q.entityType,role:"sortby",direction:W?"desc":"asc"}:null}).filter(U=>U!==null);p(g.id,{...P,sortByColumns:V})},C=M.useMemo(()=>{var A,P;return(P=(A=g.config)==null?void 0:A.sortByColumns)==null?void 0:P.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(L=g.config)==null?void 0:L.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(gi,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&E(),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"&&b&&e.jsx(bn,{variant:"outline"}),e.jsx(ji,{activeView:t,onViewChange:n}),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,{})}),b&&e.jsx(ps,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Nn,{})})]}),!w&&N&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>R(!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(_a,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Cn,{})}),t==="table"&&(S==null?void 0:S.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(S==null?void 0:S.records)||[],paginationMetadata:D,onPaginationChange:B,isLoading:T||O,onSortChange:I,sortState:C})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(S==null?void 0:S.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(mn,{sql:S==null?void 0:S.sql,error:v})]})})]}),e.jsx(bi,{isOpen:w,onClose:()=>R(!1)})]})]})}function Ci({activeField:t}){const[n,a]=M.useState(!0);return M.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(ot,{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 Si=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function wi(){var Q,q;const[t,n]=M.useState("chart"),[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),m=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);M.useEffect(()=>Si(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},y=H=>{u(H)},x=s.useEditorStore(H=>H.frame),b=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:w,removeCard:R,updateCard:N,setActiveCard:S,updateFilters:v}=s.useEditorActions(),{columns:k=[],isLoading:T,error:O}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=b,{getFieldsForContainer:E,setFieldsForContainer:I}=rt(B),{activeField:C,handleDragStart:L,handleDragEnd:A}=fi({activeCardId:x.activeCardId,sourceFields:k,getFieldsForContainer:E,setFieldsForContainer:I}),P=(H,$)=>{$&&v(H,$)},V=H=>{var $;N(H,{config:{...($=x.cards.find(F=>F.id===H))==null?void 0:$.config,filters:void 0}})},U=k,W=H=>{if(!H)return 0;let $=H.conditions.length;return H.groups.forEach(F=>{$+=W(F)}),$},ee=W(((Q=B==null?void 0:B.config)==null?void 0:Q.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:L,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Fo,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Zo,{selectedChart:h,onChartChange:y,groupByFields:E("groupBy"),pivotByFields:E("pivotBy"),metricsFields:E("metrics"),sortByFields:E("sortBy")}),e.jsx(Ni,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:f,onClear:g,onAdvancedToggle:j,onFiltersClick:p,filterCount:ee,activeCard:B,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:T,columnsError:O,getFieldsForContainer:E,cards:x.cards,activeCardId:x.activeCardId,addCard:w,setActiveCard:S})]}),!c&&m&&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"})})})]}),B&&e.jsx(pi,{cardId:B.id,filters:((q=B.config)==null?void 0:q.filters)||null,onFiltersChange:P,onClearFilters:V,availableFields:U,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ci,{activeField:C||null})})]})}function ki({authToken:t,onSave:n,onClose:a}){const r=M.useRef(null),l=s.useEditorStore(b=>b.showAIDialog),o=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:j}=el();M.useEffect(()=>{n&&d(n),a&&m(a)},[n,d,a,m]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,w;l?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(w=r.current)==null||w.resize(0))},[l,i]);function p(b){b<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(dn,{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(Co,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Dt,{})})]})]})}function x(){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(wi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Dt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:f,onDragEnd:h,onDragOver:u,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):x()})}function Di(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(ki,{onSave:l,onClose:o})})}function Ti(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=tt();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hs,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ei({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Fe,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Je,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Es,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Is,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Bs,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Fe,{className:"h-3 w-3"})})}function Ii(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=tt(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:m}=s.useColumns(),u=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const b=s.getDataType(x.dataType);return b==="number"?"metrics":(["date","string","boolean"].includes(b),"dimensions")},f=a==="all"?u:u.filter(x=>h(x)===a),g=u.filter(x=>h(x)==="dimensions").length,j=u.filter(x=>h(x)==="metrics").length,p=x=>{const b={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(b,"dashboard")};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(m)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:m.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const y=u.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>n(x.target.value)})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),f.map(x=>{const b=l==null?void 0:l.some(w=>{var R;return w.title===x.name||((R=w.column)==null?void 0:R.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),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":b}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ei,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function Ai(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Ii,{}):e.jsx(dn,{type:"filter",ColumnsComponent:()=>e.jsx(Ti,{})})})]})}function Mi(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Li(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(Mi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ai,{})})]})}function Ri(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Oi({showControls:t=!1,showFooter:n=!0,...a}){return typeof window>"u"?null:e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(Ri,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Qr,{}),e.jsxs(s.DashboardPanel,{...a,children:[e.jsx(Di,{}),e.jsx(Li,{})]})]})]})]})})}exports.DashboardPlus=Oi;exports.ResourceManagementPanel=on;exports.ScheduleDashboard=qt;exports.SelectComponent=qe;exports.cleanCard=_t;exports.downloadPdf=$t;exports.getDashbaordStateWithoutData=ls;
425
+ ON ${N}`}),j};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$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:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Mo,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(Tt,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Tt,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Ro({open:t,onOpenChange:n}){const[a,r]=M.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];M.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(y=>y.some(N=>N.name===p.name&&N.type===p.type)?y.filter(N=>!(N.name===p.name&&N.type===p.type)):[...y,p])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(a.length===0)return;const p=a[0],y=p.connectionId||"",x=p.connectionType||"",k=a.some(b=>b.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:x,mode:k,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ka,{className:"h-4 w-4"});case"model":return e.jsx(pa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const y=[];return p.database&&y.push(p.database),p.schema&&y.push(p.schema),p.name&&y.push(p.name),y.join(".")},j=p=>a.some(y=>y.name===p.name&&y.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Oo({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,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 Fo({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Bo({isVisible:t,onToggleVisibility:n}){const[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(f=>f.card.dataSource);we();const{updateDataSource:m}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...u,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:n,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:j=>{j.stopPropagation();const p=h.selectedEntities.filter(y=>!(y.name===f.name&&y.type===f.type));m({...u,...d,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(Oo,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(Fo,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(Lo,{})]})]}),e.jsx(Eo,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:u}),e.jsx(Ro,{open:l,onOpenChange:o})]})}const rs=[{id:"table",icon:Ye,label:"Table"},{id:"pivotTable",icon:Ye,label:"Pivot Table"},{id:"aggregateTable",icon:Ye,label:"Aggregate Table"},{id:"bar",icon:ms,label:"Bar Chart"},{id:"line",icon:hs,label:"Line Chart"},{id:"area",icon:Rt,label:"Area Chart"},{id:"stackedBar",icon:Bs,label:"Stacked Bar Chart"},{id:"combo",icon:da,label:"Combo Chart"},{id:"stackedLine",icon:et,label:"Stacked Line Chart"},{id:"scatter",icon:zs,label:"Scatter Chart"},{id:"bubble",icon:Xs,label:"Bubble Chart"},{id:"pie",icon:xs,label:"Pie Chart"},{id:"doughnut",icon:Vs,label:"Doughnut Chart"},{id:"funnel",icon:Zs,label:"Funnel Chart"},{id:"radar",icon:Us,label:"Radar Chart"},{id:"polarArea",icon:Js,label:"Polar Area Chart"},{id:"tornado",icon:$s,label:"Tornado Chart"},{id:"range",icon:Ps,label:"Range Chart"},{id:"kpi",icon:st,label:"KPI"},{id:"text",icon:Lt,label:"Text"},{id:"map",icon:_s,label:"Map"}],lt=t=>{const n=t.toLowerCase();for(const a of rs)if(a.id==="doughnut"){if(n.includes("doughnut")||n.includes("donut")){const r=a.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(n.includes(a.id.toLowerCase())){const r=a.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},Po="chart-selector-standard-first";function zo(){const[t,n]=s.useLocalStorageState(Po,!0);return{standardFirst:t,updatePreference:n}}const Et=({pluginVisual:t,index:n,onSelect:a})=>{const r=fs(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=lt(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},It=["default","standardPlugin","customPlugin"];function Vo({selectedChart:t,onChartChange:n}){var R;const[a,r]=M.useState(!1),{data:l}=yn();zo();const c=((R=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:R.url)||"";Ys(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:m}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:u,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),p=M.useMemo(()=>g?[g,...It.filter(b=>b!==g)]:It,[g]);function y(b){u(null),d({}),i(b),["custom","text","map"].includes(b)&&(m(!0),f(void 0)),n(b),r(!1)}function x(b){u(null),d({}),i("custom"),h({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),n("custom"),r(!1)}const N=()=>{var S;if(t==="custom"){const v=s.useEditorStore.getState().card;return((S=v==null?void 0:v.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const b=rs.find(v=>v.id===t);return(b==null?void 0:b.label)||"Select chart type"},k=()=>{var S,v;if(t==="custom"){const E=s.useEditorStore.getState().card,w=(S=E==null?void 0:E.customCardPreferences)==null?void 0:S.icon,O=(v=E==null?void 0:E.customCardPreferences)==null?void 0:v.componentName;if(w&&O)return e.jsx(_o,{icon:w,componentName:O});if(O){const D=lt(O);if(D)return D}return e.jsx(Qe,{className:"h-4 w-4"})}const b=rs.find(E=>E.id===t);if(b){const E=b.icon;return e.jsx(E,{className:"h-4 w-4"})}return e.jsx(Qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[k(),e.jsx("span",{children:N()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(b=>{if(b==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:S=>j(S?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:rs.map(S=>{const v=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>y(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(b==="standardPlugin"){const S=l.filter(v=>v.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>j(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(v=>v.componentType==="chart").map((v,E)=>e.jsx(Et,{pluginVisual:v,index:E,onSelect:()=>x(v)},`${v.url}-${v.name}-${E}`))},"standardPlugin"):null}if(b==="customPlugin"){const S=l.filter(v=>v.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>j(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((v,E)=>e.jsx(Et,{pluginVisual:v,index:E,onSelect:()=>x(v)},`${v.url}-${v.name}-${E}`))},"customPlugin"):null}return null})]})]})})]})})}const _o=({icon:t,componentName:n})=>{const a=fs(),r=lt(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Qe,{className:"h-4 w-4"})},ot=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Fe,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Je,{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(Be,{className:"h-3 w-3"})})};function Uo({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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:l?a:t,onChange:m=>{r(m.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&a!==t?(n(a),o(!1)):m.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function $o({valueAliases:t,onValueAliasesChange:n}){const[a,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{n({...t,"":""})},m=h=>{const f={...t};delete f[h],n(f)},u=h=>{const f={...t};delete f[h],f[l]=c,n(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],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(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),o(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:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function qo({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(d=>d.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:o.connectionId,cardConfig:d,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",m);const u=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",m);if(u!=null&&u.error)return console.error("Error fetching attribute values:",u.error),[];const h=t.name;return((u==null?void 0:u.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Yo({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var k,R;const c=!!l,[i,d]=M.useState(c?"values":"fields"),[m,u]=M.useState(""),[h,f]=M.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(b=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(E=>E.field.id===b.id))&&b.label.toLowerCase().includes(m.toLowerCase())}),j=b=>{f({...h,field:b}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const b={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const v=((r==null?void 0:r.conditions)||[]).map(E=>E.id===l.id?b:E);S={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,b],groups:[]}}o(S),n(!1)}},y=()=>{if(!c||!l)return;const b=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(b.length>0){const S={...r,conditions:b};o(S)}else o(void 0);n(!1)},x=b=>{f({...h,selectedValues:b})},N=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(f({id:s.v4(),field:null,selectedValues:[]}),d("fields")),u("")};return M.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(k=h.field)==null?void 0:k.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(b=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[b.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(b.value)?`${b.value.length} values`:String(b.value)})]},b.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:m,onChange:b=>u(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(b=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(b),children:[e.jsx(ot,{dataType:s.getDataType(b.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:b.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[b.entityName,".",b.name]})]})]},b.id))}),g.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),g.length===0&&!m&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Go,{field:h.field,selectedValues:h.selectedValues,onValuesChange:x,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:N,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Go({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=M.useState(""),{values:c,isLoading:i,isFetching:d}=qo({field:t,searchQuery:l,limit:500}),m=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,u=f=>{const g=n.includes(f);a(g?n.filter(j=>j!==f):[...n,f])},h=()=>{n.length===m.length&&m.length>0?a([]):a(m.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===m.length&&m.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>u(f.value),children:[e.jsx(s.Checkbox,{checked:n.includes(f.value),onCheckedChange:()=>u(f.value)}),e.jsx(gs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function Ho({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var dt,ut,mt;const{attributes:i,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:j,handleAggregationChange:p,handleDateFormatChange:y,handleGranularityChange:x,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:R,handleKpiComparisonTypeChange:b,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:w}=rt(g),[O,D]=M.useState(!1),[F,T]=M.useState(!1),[I,C]=M.useState(null),[L,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[P,V]=M.useState(t.customFormat||""),[U,W]=M.useState(!!t.customFormat),[ee,Q]=M.useState(t.granularity||"day"),[q,H]=M.useState(t.aliasTemplate||""),[$,B]=M.useState(t.valueAliases||{}),[_,Y]=M.useState((dt=t.parameters)==null?void 0:dt.filters),J=G=>{G==="custom"?W(!0):(W(!1),A(G),n==="groupBy"&&y(a,G,""))},te=G=>{V(G),n==="groupBy"&&y(a,"custom",G)},re=G=>{var me;Q(G);const ie=(me=ce(G)[0])==null?void 0:me.value;ie&&!U&&(A(ie),n==="groupBy"&&y(a,ie,"")),n==="groupBy"&&x(a,G)},ne=G=>{H(G),n==="metrics"&&N(a,G)},ue=G=>{B(G),n==="metrics"&&k(a,G)},K=G=>{j(n,a,G)},z=G=>{var oe;if(Y(G),n==="metrics"){const ie={...t,parameters:{...t.parameters,filters:G}},me=[...((oe=g.config)==null?void 0:oe.metricColumns)||[]];me[a]=ie,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:me})}T(!1)},X=()=>{R(n,a)},le={transform:s.CSS.Transform.toString(u),transition:h},ye=s.getDataType(t.dataType),ve=ye==="date",se=c==="kpi",ce=G=>{switch(G){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..."}]}},de=ce(ee),Pn=n!=="pivotBy",zn=ve&&n==="groupBy",Vn=!se&&ve&&n==="groupBy",_n=se&&ve&&n==="groupBy",Un=se&&n==="metrics"&&((ut=g.config)==null?void 0:ut.comparisonType)==="target",$n=n==="metrics",qn=()=>e.jsx("div",{onPointerDown:G=>{G.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Yn=()=>Pn?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:K,placeholder:"Display label...",type:"text"})]}):null,ct=()=>zn?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:ee,onValueChange:re,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,Gn=()=>Vn?e.jsxs(e.Fragment,{children:[ct(),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:U?"custom":L,onValueChange:J,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:de.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),U&&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:P,onChange:G=>{G.stopPropagation(),te(G.target.value)},onClick:G=>G.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,Hn=()=>{var G,oe,ie,me,ke;return _n?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:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:b,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:((oe=g.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:S})]})}),((ie=g.config)==null?void 0:ie.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:((me=g.config)==null?void 0:me.trendlineWindow)||30,onChange:Ze=>{const Xn=parseInt(Ze.target.value)||30;v(Xn)},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:((ke=g.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Kn=()=>{var G,oe;return Un?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(Ne,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((oe=g.config)==null?void 0:oe.targetValue)!==null?String(g.config.targetValue):"",onSave:ie=>{!isNaN(Number(ie))&&ie!==null?w(Number(ie)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},Qn=()=>$n?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:G=>{p(a,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{C(G),T(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((oe,ie)=>e.jsx("div",{children:String(oe)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var me;oe.stopPropagation();const ie=_.conditions.filter(ke=>ke.id!==G.id);if(ie.length>0){const ke={..._,conditions:ie};z(ke)}else if(Y(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Ze=[...((me=g.config)==null?void 0:me.metricColumns)||[]];Ze[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ze})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{C(null),T(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Rn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Uo,{aliasTemplate:q,onAliasTemplateChange:ne}),e.jsx($o,{valueAliases:$,onValueAliasesChange:ue})]})]}):null,{columns:Wn=[]}=s.useColumns(),Jn=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:m,style:le,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ot,{dataType:ye}),e.jsx(gs,{className:s.cn("w-[140px] flex-1 text-sm",Jn&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((mt=_==null?void 0:_.conditions)==null?void 0:mt.length)&&!O&&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-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),D(!O)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${O?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const oe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",oe),l(oe)},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:G=>{G.stopPropagation(),X()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[qn(),Yn(),c==="kpi"&&ct(),Gn(),Hn(),Kn(),Qn()]})]}),F&&e.jsx(Yo,{open:F,onOpenChange:G=>{T(G),G||C(null)},availableFields:Wn,existingFilters:_,editingCondition:I,onSave:G=>{var oe;if(G)z(G);else if(Y(void 0),n==="metrics"){const ie={...t,parameters:{...t.parameters,filters:void 0}},me=[...((oe=g.config)==null?void 0:oe.metricColumns)||[]];me[a]=ie,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:me})}C(null)}})]})}function Ko({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$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:n()})]})})}function ts({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(j=>j.card),u=s.useEditorStore(j=>j.card.type),h=n.length>0,f=(j,p)=>{var x;!((x=m.config)!=null&&x.sortByColumns)||m.config.sortByColumns.findIndex(N=>N.id===j)===-1||d(m.id,j,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Ko,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 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:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map((j,p)=>{const x=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Ho,{field:j,zone:t,index:p,sortDirection:x,onSortDirectionChange:N=>f(j.id,N),hasPivotColumns:o,cardType:u})})},j.id)})})})})]})}const At=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Qo=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ds({value:t,onChange:n,label:a}){const[r,l]=M.useState(!1),[o,c]=M.useState(!1),i=()=>{const d=At.find(m=>m.value===t);return d?d.color:t.startsWith("#")?t:At[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Qo.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Tn,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ns={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
426
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Wo(){var i,d,m,u,h,f,g,j,p,y;const t=s.useEditorStore(x=>x.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((u=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:u.metricComparison)||{},c=x=>{var k;const N={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...o,...x}}};n(N)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ns).map(([x,N])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:N.label},x))})]}),(()=>{var N,k,R;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=ns[x])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(k=ns[x])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=ns[x])==null?void 0:R.example]})]})})()]}),e.jsx(nt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ds,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(Ds,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(Ds,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Jo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(nt,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Xo({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(j=>{var p;return((p=j.card.customCardPreferences)==null?void 0:p.url)&&j.card.type==="custom"}),o=s.useEditorStore(j=>j.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",m=c!=="kpi"&&i,u=["pie","doughnut","polar","funnel"].includes(c),h=d&&!u,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Aa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ts,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(ts,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ts,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),m&&e.jsx(ts,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Jo,{}),e.jsx(Wo,{}),e.jsx(En,{}),e.jsx(In,{}),e.jsx(An,{}),e.jsx(Mn,{})]})})]})]})}function Zo({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(Vo,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||u}),children:e.jsx(ps,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Xo,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function ei({initialFilters:t,availableFields:n}={}){const[a,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(b=>b.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=b=>{const S=v=>{if(v.id===b){const E=i[0]||d;return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:E,operator:"=",value:""}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},u=b=>{const S=v=>{if(v.id===b){const E=i[0]||d;return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:"=",value:""}],groups:[]}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},h=(b,S)=>{const v=E=>E.id===b?{...E,conditions:E.conditions.filter(w=>w.id!==S)}:{...E,groups:E.groups.map(v)};r(v(a))},f=(b,S)=>{const v=E=>E.id===b?{...E,groups:E.groups.filter(w=>w.id!==S)}:{...E,groups:E.groups.map(v)};r(v(a))},g=(b,S,v,E)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=O=>O.id===b?{...O,conditions:O.conditions.map(D=>D.id===S?{...D,[v]:E}:D)}:{...O,groups:O.groups.map(w)};r(w(a))},j=(b,S,v)=>{const E=w=>w.id===b?{...w,conditions:w.conditions.map(O=>O.id===S?{...O,...v}:O)}:{...w,groups:w.groups.map(E)};r(E(a))},p=(b,S)=>{const v=E=>E.id===b?{...E,logicalOperator:S}:{...E,groups:E.groups.map(v)};r(v(a))},y=(b,S)=>{const v=E=>E.id===b?{...E,negate:S}:{...E,groups:E.groups.map(v)};r(v(a))},x=(b,S,v)=>{const E=w=>w.id===b?{...w,conditions:s.arrayMove(w.conditions,S,v)}:{...w,groups:w.groups.map(E)};r(E(a))},N=(b,S,v)=>{const E=w=>w.id===b?{...w,groups:s.arrayMove(w.groups,S,v)}:{...w,groups:w.groups.map(E)};r(E(a))},k=b=>{if(!b||b.conditions.length===0&&b.groups.length===0)return"-- No filters defined";const S=E=>{let w="";typeof E.field=="object"?w=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:w=String(E.field);const O=E.operator;let D=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(E.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(E.operator)){let F=[];Array.isArray(D)?F=D.map(T=>typeof T=="string"?`'${T}'`:String(T)):typeof D=="string"?F=D.split(",").map(T=>{const I=T.trim();return E.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(F=[String(D)]),D=`(${F.join(", ")})`}switch(O){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} ${O} ${D}`}},v=E=>{const w=E.conditions.map(S),O=E.groups.map(I=>v(I)),D=[...w,...O].filter(Boolean);if(D.length===0)return"";const F=D.join(` ${E.logicalOperator} `),T=D.length>1?`(${F})`:F;return E.negate?`NOT ${T}`:T};return v(b)},R=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:u,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:j,updateGroupOperator:p,updateGroupNegate:y,reorderConditions:x,reorderGroups:N,generateSQLPreview:k,hasAnyFilters:R}}function si({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const ti=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(ya,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},ni=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ai({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return a.forEach(m=>{const u=ni(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][m.entityId].push(m)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(si,{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,m])=>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(m).map(([u,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:[ti(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{n(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+g))]},`${d}-${u}`))},d))})]})})]})}function it(t){var j;const n=s.useEditorStore(p=>p.card),{authToken:a}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},m=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:u,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",(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:n.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(p=>({label:p[t.name]||"BLANK",value:p[t.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function ri({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=xe.useState(!1),{filterValues:i}=it(t),d=u=>{a(n.filter(h=>h!==u))},m=u=>{n.includes(u)?a(n.filter(h=>h!==u)):a([...n,u])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(u=>{const h=i.find(f=>f.value===u);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(u)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):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((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const Fn=t=>{if(!t)return 0;let n=t.conditions.length;return t.groups.forEach(a=>{n+=Fn(a)}),n};function li({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=it(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const oi=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],ii=["=","!=","contains","startsWith","endsWith","in","not in"],ci=["=","!=",">",">=","<","<=","in","not in"],di=["=","!="],ui=["=","!=",">",">=","<","<=","in","not in"];function mi(t){switch(t){case"string":return ii;case"number":return ci;case"boolean":return di;case"date":return ui;default:return oi}}function Bn({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:u,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:p,error:y}=it(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...u,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(ai,{value:t.field,onValueChange:N=>{d(a,t.id,{field:N,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(a,t.id,{operator:N,value:[]}):d(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:mi(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:N},N))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ri,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(a,t.id,{value:N}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:N=>d(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(li,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(a,t.id,{value:N}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:N=>d(a,t.id,{value:N==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(a,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function hi({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:j,updateConditionFields:p}){const{attributes:y,listeners:x,setNodeRef:N,transform:k,transition:R,isDragging:b}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(k),transition:R},v=w=>{const{active:O,over:D}=w;if(D&&O.id!==D.id){const F=t.conditions.findIndex(I=>I.id===O.id),T=t.conditions.findIndex(I=>I.id===D.id);F!==-1&&T!==-1&&m(t.id,F,T)}},E=w=>{const{active:O,over:D}=w;if(D&&O.id!==D.id&&a){const F=t.groups.findIndex(I=>I.id===O.id),T=t.groups.findIndex(I=>I.id===D.id);F!==-1&&T!==-1&&u(a,F,T)}};return e.jsxs("div",{ref:N,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${b?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...y,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange: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:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,O)=>e.jsx(Bn,{condition:w,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>j(w,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function xi({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:u,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:p,reorderConditions:y,reorderGroups:x,generateSQLPreview:N,hasAnyFilters:k,setCurrentFilters:R}=ei({initialFilters:t,availableFields:n}),b=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,v]=M.useState(!1),E=(D,F,T)=>{const I=C=>C.id===D?{...C,conditions:C.conditions.map(L=>L.id===F?{...L,field:T,dataType:T.dataType}:L)}:{...C,groups:C.groups.map(I)};R(I(o))},w=(D,F=0,T)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:C,over:L}=I;if(L&&C.id!==L.id){const A=D.conditions.findIndex(V=>V.id===C.id),P=D.conditions.findIndex(V=>V.id===L.id);A!==-1&&P!==-1&&y(D.id,A,P)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,C)=>e.jsx(Bn,{condition:I,index:C,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:f,onUpdateField:E,onRemoveCondition:u,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},I.id))})}),e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:C,over:L}=I;if(L&&C.id!==L.id){const A=D.groups.findIndex(V=>V.id===C.id),P=D.groups.findIndex(V=>V.id===L.id);A!==-1&&P!==-1&&x(D.id,A,P)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,F+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:()=>m(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(hi,{group:D,depth:F,parentGroupId:T,onUpdateGroupOperator:j,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:E,onRemoveCondition:u,onReorderConditions:y,onReorderGroups:x,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:w,updateConditionFields:g},D.id),O=Fn(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(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>v(!!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)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(k?o:null),children:"Apply Filters"})]})]})}function pi({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=m=>{a(t,m),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.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(xi,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function fi({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=M.useState(null),c=s.useEditorStore(j=>j.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],m=M.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(p=>p.id===j)?"source":a("groupBy").find(p=>p.id===j)?"groupBy":a("metrics").find(p=>p.id===j)?"metrics":a("pivotBy").find(p=>p.id===j)?"pivotBy":a("sortBy").find(p=>p.id===j)?"sortBy":null,[n,a]),u=M.useCallback(j=>{o(j.active.id)},[]),h=M.useCallback(j=>{const{active:p,over:y}=j;if(!y||!t){o(null);return}const x=p.id,N=y.id,k=m(x),R=m(N)||N;if(k==="source"&&R==="sortBy"){o(null);return}if(k==="source"&&R!=="source"&&R!=="sortBy"){const b=[...n].find(w=>w.id===x);if(!b){o(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){o(null);return}if(w!==b.qualifiedEntityName&&b.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(w,b.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(R);if(s.fieldAlreadyExists(b,v)){o(null);return}const E=s.getNewField(b,R,v);o(null),r(R,[...v,E]);return}if(k&&R&&k!=="source"&&R!=="source"&&k!==R){const b=a(k),S=a(R),v=b.find(O=>O.id===x);if(!v){o(null);return}const E=s.getNewField(v,R,S);if(o(null),R==="sortBy"){if(k==="pivotBy"){o(null);return}s.fieldAlreadyExists(v,S)||r(R,[...S,E]);return}const w=b.filter(O=>O.id!==x);r(k,w),r(R,[...S,E]);return}if(k&&R&&k===R&&k!=="source"){const b=a(k),S=b.findIndex(E=>E.id===x),v=b.findIndex(E=>E.id===N);if(S!==v){const E=s.arrayMove(b,S,v);r(k,E)}}o(null)},[t,n,a,r,m,i]),f=l?d.find(j=>j.id===l):null;return{activeId:l,activeField:f,handleDragStart:u,handleDragEnd:h}}function gi({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=we();r==null||r.role;const[l,o]=M.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:m}=M.useContext(s.SemaphorContext).tokenProps,u=(m==null?void 0:m.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),j=s.useManagementStore(x=>x.selectedVisual),p=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!u&&"justify-end"),children:[u&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx(Ws,{}),a&&!p&&e.jsx(Qs,{variant:"default"}),p&&e.jsx(hl,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function ji({activeView:t,onViewChange:n}){const a=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-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"}),a.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const yi=[{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,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=M.useState(!1),[l,o]=M.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),n(t.id,parseInt(u))},i=u=>{const h=u.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:yi.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function bi({isOpen:t,onClose:n}){const a=Xt(n,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(u=>u.card),o=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:m&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ni({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:u,columnsLoading:h,columnsError:f}){var L;const g=s.useEditorStore(A=>A.card);s.useEditorStore(A=>A.frame);const j=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:p,setCard:y,updateCardInFrame:x}=s.useEditorActions(),N=s.useEditorStore(A=>A.showAIDialog),[k,R]=M.useState(!1),b=s.useEditorStore(A=>{var P;return((P=A.card.customCardPreferences)==null?void 0:P.url)&&A.card.type==="custom"}),{data:S,errorMessage:v,isPending:E,isLoading:w,isFetching:O,pagination:D}=s.useDashboardCardQuery(m),F=(A,P)=>{const V={...m,paginationConfig:{page:A+1,pageSize:P}};y(V),x(V)};function T(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(j||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.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(u.slice(0,5),null,2)})]})]})})}const I=A=>{if(!g.config)return;if(!A.length){p(g.id,{...g.config,sortByColumns:[]});return}const P=g.config,V=A.map(({id:U,desc:W})=>{var H,$;const ee=(H=P.metricColumns)==null?void 0:H.find(B=>B.label===U),Q=($=P.groupByColumns)==null?void 0:$.find(B=>B.label===U),q=ee||Q;return q?{id:s.getFieldId("sortBy",q),name:q.name,dataType:q.dataType,label:q.label,qualifiedEntityName:q.qualifiedEntityName,entityId:q.entityId,entityName:q.entityName,entityType:q.entityType,role:"sortby",direction:W?"desc":"asc"}:null}).filter(U=>U!==null);p(g.id,{...P,sortByColumns:V})},C=M.useMemo(()=>{var A,P;return(P=(A=g.config)==null?void 0:A.sortByColumns)==null?void 0:P.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(L=g.config)==null?void 0:L.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(gi,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&T(),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"&&N&&e.jsx(bn,{variant:"outline"}),e.jsx(ji,{activeView:t,onViewChange:n}),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,{})}),N&&e.jsx(ps,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Nn,{})})]}),!k&&b&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>R(!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(_a,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Cn,{})}),t==="table"&&(S==null?void 0:S.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(S==null?void 0:S.records)||[],paginationMetadata:D,onPaginationChange:F,isLoading:w||O,onSortChange:I,sortState:C})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(S==null?void 0:S.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(mn,{sql:S==null?void 0:S.sql,error:v})]})})]}),e.jsx(bi,{isOpen:k,onClose:()=>R(!1)})]})]})}function Ci({activeField:t}){const[n,a]=M.useState(!0);return M.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(ot,{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 Si=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function wi(){var Q,q;const[t,n]=M.useState("chart"),[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),m=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);M.useEffect(()=>Si(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},y=H=>{u(H)},x=s.useEditorStore(H=>H.frame),N=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:k,removeCard:R,updateCard:b,setActiveCard:S,updateFilters:v}=s.useEditorActions(),{columns:E=[],isLoading:w,error:O}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),F=N,{getFieldsForContainer:T,setFieldsForContainer:I}=rt(F),{activeField:C,handleDragStart:L,handleDragEnd:A}=fi({activeCardId:x.activeCardId,sourceFields:E,getFieldsForContainer:T,setFieldsForContainer:I}),P=(H,$)=>{$&&v(H,$)},V=H=>{var $;b(H,{config:{...($=x.cards.find(B=>B.id===H))==null?void 0:$.config,filters:void 0}})},U=E,W=H=>{if(!H)return 0;let $=H.conditions.length;return H.groups.forEach(B=>{$+=W(B)}),$},ee=W(((Q=F==null?void 0:F.config)==null?void 0:Q.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:L,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Bo,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Zo,{selectedChart:h,onChartChange:y,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy")}),e.jsx(Ni,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:f,onClear:g,onAdvancedToggle:j,onFiltersClick:p,filterCount:ee,activeCard:F,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:E,columnsLoading:w,columnsError:O,getFieldsForContainer:T,cards:x.cards,activeCardId:x.activeCardId,addCard:k,setActiveCard:S})]}),!c&&m&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),F&&e.jsx(pi,{cardId:F.id,filters:((q=F.config)==null?void 0:q.filters)||null,onFiltersChange:P,onClearFilters:V,availableFields:U,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ci,{activeField:C||null})})]})}function ki({authToken:t,onSave:n,onClose:a}){const r=M.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:j}=el();M.useEffect(()=>{n&&d(n),a&&m(a)},[n,d,a,m]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var N,k;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[l,i]);function p(N){N<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(dn,{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(Co,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Dt,{})})]})]})}function x(){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(wi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Dt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:f,onDragEnd:h,onDragOver:u,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):x()})}function Di(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(ki,{onSave:l,onClose:o})})}function Ti(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=tt();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hs,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ei({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Fe,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Je,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Es,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Is,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Fs,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})})}function Ii(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=tt(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:m}=s.useColumns(),u=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const N=s.getDataType(x.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},f=a==="all"?u:u.filter(x=>h(x)===a),g=u.filter(x=>h(x)==="dimensions").length,j=u.filter(x=>h(x)==="metrics").length,p=x=>{const N={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(N,"dashboard",x)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(m)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:m.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const y=u.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>n(x.target.value)})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),f.map(x=>{const N=l==null?void 0:l.some(k=>{var R;return k.title===x.name||((R=k.column)==null?void 0:R.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ei,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function Ai(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Ii,{}):e.jsx(dn,{type:"filter",ColumnsComponent:()=>e.jsx(Ti,{})})})]})}function Mi(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Li(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(Mi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ai,{})})]})}function Ri(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Oi({showControls:t=!1,showFooter:n=!0,...a}){return typeof window>"u"?null:e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(Ri,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Qr,{}),e.jsxs(s.DashboardPanel,{...a,children:[e.jsx(Di,{}),e.jsx(Li,{})]})]})]})]})})}exports.DashboardPlus=Oi;exports.ResourceManagementPanel=on;exports.ScheduleDashboard=qt;exports.SelectComponent=qe;exports.cleanCard=_t;exports.downloadPdf=$t;exports.getDashbaordStateWithoutData=ls;