react-semaphor 0.0.541 → 0.0.542
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.
- package/dist/chunks/{dashboard-plus-C-r2MYZc.js → dashboard-plus-1gaqwTwW.js} +20 -20
- package/dist/chunks/{dashboard-plus-CP6GZeS2.js → dashboard-plus-Cwov-m_K.js} +436 -439
- package/dist/chunks/{index-B1NWaCy2.js → index-Df9f4B_x.js} +1 -1
- package/dist/chunks/{index-CTwDj1wp.js → index-tok2NXq1.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var st=t=>{throw TypeError(t)};var ds=(t,a,n)=>a.has(t)||st("Cannot "+n);var re=(t,a,n)=>(ds(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?st("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(ds(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(ds(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-Df9f4B_x.js"),M=require("react");require("react-dom");function Rn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Rn(M);var be,Ne,de,fe,ge,We,ys,jt,On=(jt=class extends s.Subscribable{constructor(a,n){super();Oe(this,ge);Oe(this,be);Oe(this,Ne);Oe(this,de);Oe(this,fe);Be(this,be,a),this.setOptions(n),this.bindMethods(),Fe(this,ge,We).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,be).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,be).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Fe(this,ge,We).call(this),Fe(this,ge,ys).call(this,a)}getCurrentResult(){return re(this,Ne)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),Fe(this,ge,We).call(this),Fe(this,ge,ys).call(this)}mutate(a,n){var r;return Be(this,fe,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,be).getMutationCache().build(re(this,be),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},be=new WeakMap,Ne=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakSet,We=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Ne,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},ys=function(a){s.notifyManager.batch(()=>{var n,r,o,i,c,l,d,u;if(re(this,fe)&&this.hasListeners()){const h=re(this,Ne).variables,m=re(this,Ne).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,fe)).onSuccess)==null||r.call(n,a.data,h,m),(i=(o=re(this,fe)).onSettled)==null||i.call(o,a.data,null,h,m)):(a==null?void 0:a.type)==="error"&&((l=(c=re(this,fe)).onError)==null||l.call(c,a.error,h,m),(u=(d=re(this,fe)).onSettled)==null||u.call(d,void 0,a.error,h,m))}this.listeners.forEach(h=>{h(re(this,Ne))})})},jt);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new On(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=ue.useCallback((c,l)=>{r.mutate(c,l).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:i,mutateAsync:o.mutate}}/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const yt=s.createLucideIcon("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
|
|
67
67
|
* @license lucide-react v0.453.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const tt=s.createLucideIcon("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/**
|
|
82
82
|
* @license lucide-react v0.453.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const vt=s.createLucideIcon("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/**
|
|
92
92
|
* @license lucide-react v0.453.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
@@ -133,7 +133,7 @@
|
|
|
133
133
|
*
|
|
134
134
|
* This source code is licensed under the ISC license.
|
|
135
135
|
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const
|
|
136
|
+
*/const bt=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
137
137
|
* @license lucide-react v0.453.0 - ISC
|
|
138
138
|
*
|
|
139
139
|
* This source code is licensed under the ISC license.
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
*
|
|
169
169
|
* This source code is licensed under the ISC license.
|
|
170
170
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
171
|
+
*/const Nt=s.createLucideIcon("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/**
|
|
172
172
|
* @license lucide-react v0.453.0 - ISC
|
|
173
173
|
*
|
|
174
174
|
* This source code is licensed under the ISC license.
|
|
@@ -248,7 +248,7 @@
|
|
|
248
248
|
*
|
|
249
249
|
* This source code is licensed under the ISC license.
|
|
250
250
|
* See the LICENSE file in the root directory of this source tree.
|
|
251
|
-
*/const
|
|
251
|
+
*/const Ct=s.createLucideIcon("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
|
|
252
252
|
* @license lucide-react v0.453.0 - ISC
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
@@ -283,12 +283,12 @@
|
|
|
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
|
|
286
|
+
*/const nt=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
287
287
|
* @license lucide-react v0.453.0 - ISC
|
|
288
288
|
*
|
|
289
289
|
* This source code is licensed under the ISC license.
|
|
290
290
|
* See the LICENSE file in the root directory of this source tree.
|
|
291
|
-
*/const
|
|
291
|
+
*/const at=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
292
292
|
* @license lucide-react v0.453.0 - ISC
|
|
293
293
|
*
|
|
294
294
|
* This source code is licensed under the ISC license.
|
|
@@ -313,7 +313,7 @@
|
|
|
313
313
|
*
|
|
314
314
|
* This source code is licensed under the ISC license.
|
|
315
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const
|
|
316
|
+
*/const St=s.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
317
317
|
* @license lucide-react v0.453.0 - ISC
|
|
318
318
|
*
|
|
319
319
|
* This source code is licensed under the ISC license.
|
|
@@ -323,7 +323,7 @@
|
|
|
323
323
|
*
|
|
324
324
|
* This source code is licensed under the ISC license.
|
|
325
325
|
* See the LICENSE file in the root directory of this source tree.
|
|
326
|
-
*/const
|
|
326
|
+
*/const wt=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
|
|
327
327
|
* @license lucide-react v0.453.0 - ISC
|
|
328
328
|
*
|
|
329
329
|
* This source code is licensed under the ISC license.
|
|
@@ -353,7 +353,7 @@
|
|
|
353
353
|
*
|
|
354
354
|
* This source code is licensed under the ISC license.
|
|
355
355
|
* See the LICENSE file in the root directory of this source tree.
|
|
356
|
-
*/const
|
|
356
|
+
*/const Dt=s.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
357
357
|
* @license lucide-react v0.453.0 - ISC
|
|
358
358
|
*
|
|
359
359
|
* This source code is licensed under the ISC license.
|
|
@@ -373,7 +373,7 @@
|
|
|
373
373
|
*
|
|
374
374
|
* This source code is licensed under the ISC license.
|
|
375
375
|
* See the LICENSE file in the root directory of this source tree.
|
|
376
|
-
*/const
|
|
376
|
+
*/const kt=s.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
377
377
|
* @license lucide-react v0.453.0 - ISC
|
|
378
378
|
*
|
|
379
379
|
* This source code is licensed under the ISC license.
|
|
@@ -383,7 +383,7 @@
|
|
|
383
383
|
*
|
|
384
384
|
* This source code is licensed under the ISC license.
|
|
385
385
|
* See the LICENSE file in the root directory of this source tree.
|
|
386
|
-
*/const
|
|
386
|
+
*/const Tt=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
|
|
387
387
|
* @license lucide-react v0.453.0 - ISC
|
|
388
388
|
*
|
|
389
389
|
* This source code is licensed under the ISC license.
|
|
@@ -393,7 +393,7 @@
|
|
|
393
393
|
*
|
|
394
394
|
* This source code is licensed under the ISC license.
|
|
395
395
|
* See the LICENSE file in the root directory of this source tree.
|
|
396
|
-
*/const
|
|
396
|
+
*/const Et=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"}]]);/**
|
|
397
397
|
* @license lucide-react v0.453.0 - ISC
|
|
398
398
|
*
|
|
399
399
|
* 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 je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Os(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>At(c))}})}})}}function At(t){return{...t,customCfg:La(t.customCfg),data:[]}}function La(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ra(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function vs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function Oa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Ba(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[l,d]=M.useState(!1),[u,h]=M.useState(!1),m=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function g(){d(!0);const x=Os(m),v=await Ra(t,x,p,f==null?void 0:f.accessToken);v&&(i([...o||[],v]),c(v.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:h,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:l,children:l?"Creating...":"Add"})})]})]})}function Fa(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:o,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function l(h){i(h)}async function d(h){if(await Oa(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==h);o(p||[]),i("original")}}async function u(h){const m=n==null?void 0:n.map(g=>g.id===h.id?{...g,isDefault:!h.isDefault}:{...g,isDefault:!1});o(m||[]);const p={...h,isDefault:!h.isDefault};await vs(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(g=>g.isDefault);if(f&&f.id!==h.id){const g={...f,isDefault:!1};await vs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(da,{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:l,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:m=>{m.preventDefault(),u(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:m=>{m.preventDefault(),d(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Mt(){var i;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(i=s.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Lt(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Mt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const l=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(l,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,m=document.createElement("a");m.href=h;const p=`${o}-${new Date().toISOString()}.pdf`;m.download=p,m.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function Pa({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Lt()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:l=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),l&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ot=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Rt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=za(),[l,d]=M.useState(""),[u,h]=M.useState(ot[0].value),[m,p]=M.useState("06:00"),[f,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:l,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:f,onChange:x=>{g(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ot,value:u,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:m,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:l,frequency:u,time:m,subject:f}),p("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!l,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(Nt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(it,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Xn,{className:"size-3.5"})}),e.jsx(it,{tooltip:`${x.endUserEmail}`,children:e.jsx(ya,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const it=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function za(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,i]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),l=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",m={dashboardId:l,endUserId:u},{data:p,isLoading:f,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",l,u],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",m),enabled:!!(c!=null&&c.accessToken)&&!!l&&!!u});async function j({email:C,subject:R,frequency:T,time:S}){const{authToken:N,...k}=Mt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:T,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:l,dashboardParams:k};a("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(D,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";i(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{i(null)},2e3)}catch(T){console.error(T),i(null),a("error"),r(T.message)}}return{data:p,isLoading:f,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function os(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:i}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const l=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!l.ok)throw new Error("Failed to fetch user info");return(await l.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:i}}function Ot(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const _a=async(t,a,n,r,o,i)=>{const c={},l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${l[a]}`,t,c)},Va=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Ua=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},i=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!i.ok){const c=await i.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${i.status}`)}return i.json()},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const i=await o.json();throw new Error((i==null?void 0:i.error)||`HTTP error! status: ${o.status}`)}return o.json()},qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},Ga=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Ha=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},i=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!i.ok){const c=await i.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${i.status}`)}return i.json()},Ka=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},Qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Wa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ja(t,a,n,r,o){const{authToken:i}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>_a((i==null?void 0:i.accessToken)||"",t),enabled:!!(i!=null&&i.accessToken)})}function Ya(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Va((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Xa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Ua((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Za(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>$a((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function er(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>qa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function sr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ga((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function tr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ha((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function nr(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ka((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function ar(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>Qa((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function rr(t,a){return ar(ee.VISUAL,t,a)}function Bt(){const[t,a]=M.useState(new Map),n=M.useCallback((i,c)=>{a(l=>{const d=new Map(l),u=new Set(d.get(i)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(i,u),d})},[]),r=M.useCallback((i,c)=>{a(l=>{const d=new Map(l),u=new Set(d.get(i)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(i):d.set(i,u),d})},[]),o=M.useCallback((i,c)=>{const l=t.get(i);return l?c?l.has(c):l.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Ft(t,a,n){var m;const r=Ja(t),o=Ya(t,n),i=Xa(t),c=Za(t,a),l=er(t),d=sr(),u=tr(),h={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((m=r.data)==null?void 0:m[h[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:i.mutate,deleteResource:c.mutate,duplicateResource:l.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:i.isPending,isDeleting:c.isPending,isDuplicating:l.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function or(t,a){return Ft(ee.DASHBOARD,t,a)}function ir(t,a){return Ft(ee.VISUAL,t,a)}function lr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function cr({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:i,onEditVisual:c,onUpdateVisual:l,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:h,formatDate:m}){var T;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(St,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{p(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>l==null?void 0:l(t.id,{title:S}),isEditable:t.ownership.isOwner&&f,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>l==null?void 0:l(t.id,{description:S}),isEditable:t.ownership.isOwner&&f,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),i(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(Sa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),h(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function Pt({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Ye({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:i=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,l=n.filter(u=>u.value!==t);return i?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:i}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:l.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function zt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(i=>n(i.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(i=>{const c=t.find(d=>d.id===i.id),l=o(i.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[i.name,e.jsx(Ye,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(i.id,d),roleOptions:l}),e.jsx("button",{onClick:()=>n(i.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id)})}),e.jsx(s.Separator,{})]})}function _t({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Vt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),i=l=>{const d=a.find(u=>u.id===l);return(d==null?void 0:d.name)||"Unknown User"},c=l=>{const d=o.find(u=>u.value===l);return(d==null?void 0:d.label)||l};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(l=>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:i(l.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(l.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(l.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(l.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id))})]})}function Ut(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const i=c=>{const l=c.target;o.current&&o.current.contains(l)||l instanceof Element&&(l.closest("[data-radix-popper-content-wrapper]")||l.closest("[data-radix-select-content]")||l.closest("[data-radix-popover-content]")||l.closest("[data-radix-dropdown-menu-content]")||l.closest("[data-radix-tooltip-content]")||l.closest('[role="listbox"]')||l.closest('[role="option"]')||l.closest('[role="combobox"]'))||l instanceof Element&&l.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,i),()=>{document.removeEventListener(r,i)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function dr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function $t(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ur(t,a,n){const r=$t(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(l=>l.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(l=>l.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(l=>l.tenantUserId===t.id)}function mr({user:t}){return $t(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 hr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:i}){if(!(a!=null&&a.role))return null;const c=dr((r==null?void 0:r.type)||""),l=n.some(m=>m.id===t.id),d=n.find(m=>m.id===t.id),u=d?d.newRole:a==null?void 0:a.role,h=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Ye,{currentRole:u,onRoleChange:m=>{i(t.id,a.role,m)},roleOptions:h,disabled:!c,allowDropdown:c,className:l?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:xe(u,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function xr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx($e,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function pr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function fr({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,l=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],h=c.orgUsersOnly||[],m=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:[l.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 (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((p,f)=>{var j,b;const g=((j=a.find(C=>C.id===p.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===p.orgUserId))==null?void 0:b.type)||"",v=xe(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},f)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.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((p,f)=>{var j,b;const g=((j=a.find(C=>C.id===p.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===p.tenantUserId))==null?void 0:b.type)||"",v=xe(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},f)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),h.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:h.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),m.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:m.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),!l.length&&!d.length&&!u.length&&!h.length&&!m.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],l=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var f,g;const h=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",p=xe(d.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),l.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:l.map((d,u)=>{const h=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)})})]}),!c.length&&!l.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const i=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:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((l,d)=>{var p,f;const u=((p=a.find(g=>g.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((f=a.find(g=>g.id===l.tenantUserId))==null?void 0:f.type)||"",m=xe(l.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.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((l,d)=>{const u=xe(l.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!i.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function gr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function jr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:i,selectedUser:c,roleOptions:l,currentUser:d,usersToUpdate:u,handleUserToggle:h,handleRemoveAccess:m,handleUpdateAccess:p,handleUserRoleChange:f}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":i?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:i,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?h(t.id):m(t.id):h(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(mr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Ye,{currentRole:a==null?void 0:a.role,onRoleChange:g=>p(t.id,a.role,g),roleOptions:l,disabled:!1,allowDropdown:!0}):e.jsx(hr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>l,handleUpdateAccess:p}),i&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(Ye,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>f(t.id,g),roleOptions:l,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(xr,{hasAccess:r,isUserRemoving:n,isSelected:i,hasAccessFromAPI:o}),e.jsx(pr,{isUserRemoving:n,isSelected:i,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function qt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:i,handleUserToggle:c,handleUserRoleChange:l,handleRemoveAccess:d,handleUpdateAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(T=>{const S=h.some(k=>k.id===T),N=m.includes(T);S?g.removeSelectedUser(T):N?g.removeUserFromRemove(T):g.addSelectedUser({id:T,role:"VIEWER"})}),v=l||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((T,S,N)=>{g.addUserToUpdate({id:T,currentRole:S,newRole:N})}),C=o,R=m;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(fr,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:i})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(T=>({id:T.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(gr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(T=>{const S=t?ur(T,t,i):void 0,N=R.includes(T.id),k=!!S,w=k&&!N,L=h.some(A=>A.id===T.id),D=h.find(A=>A.id===T.id),O=r(T.type);return e.jsx(jr,{user:T,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:D,roleOptions:O,currentUser:i,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},T.id)})]})]})}function Gt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(i=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:i.value,id:i.value,className:"peer sr-only",disabled:i.disabled}),e.jsxs(s.Label,{htmlFor:i.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 ${i.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[i.icon||e.jsx(Se,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:i.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.description})]})]})]},i.value))}),!o&&r.some(i=>i.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 ke=()=>[{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 yr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:i=!1,isUpdating:c=!1,isRemoving:l=!1}){const d=s.useShareCurrentMode(),u=ke().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",m=o?o.newRole:h,p=a.role!=="NONE"&&!i&&(!o||o.newRole===h),f=o!==null&&o.newRole!==h,g=i,x=h==="NONE"||!h,v=b=>{switch(b){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ta,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(h,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",f&&!g&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":g||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),f&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(b=>e.jsxs(s.Button,{variant:m===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||l,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Ht({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:i,onRemoveAccess:c,allUsersToUpdate:l,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,m=a?{role:u(a.role)}:{role:"NONE"},p=l?{currentRole:u(l.currentRole),newRole:u(l.newRole)}:null,f=(x,v)=>{i(x,v)},g=()=>{c()};return e.jsx(yr,{currentUser:t,currentShare:m,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:f,onRemoveAccess:g,allUsersToUpdate:p,allUsersToRemove:d})}const vr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function br(t={}){var r,o,i;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>vr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,l)=>l instanceof Error&&l.message.includes("401")||l instanceof Error&&l.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((i=n.data)==null?void 0:i.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:i}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&i?{tenantId:i}:{}}),[a,o,i]),{users:l,isLoading:d,isError:u}=br(c),h=nr(r,n);return{allUsers:l,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function Nr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var W,V;const l=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:h,debouncedSearchQuery:m}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(l==="org")return"organization";if(l==="tenant")return"tenant"},T=()=>{if(l==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:k}=we({debouncedSearchQuery:m,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:T()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),D=S.filter($=>p.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=p.some(Z=>Z.id===$),U=f.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},E=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},P=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const z=k,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Pt,{value:u,onChange:h}),e.jsx(zt,{selectedUsers:p,selectedUserObjects:D,onRemove:O,onRoleChange:A,getRoleOptions:ke}),e.jsx(_t,{usersToRemove:f,allUsers:L,onRemove:y}),e.jsx(Vt,{usersToUpdate:g,allUsers:L,onRemove:E,getRoleOptions:ke}),e.jsx(qt,{existingShares:N,isInitialLoading:z,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:ke,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Ht,{currentUser:n,currentShare:_,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:F,onRemoveAccess:P,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function lt({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var Q;const{searchQuery:l,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=Wa({enabled:(n==null?void 0:n.type)==="organization"}),[R,T]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;T(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:D,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=h.some(K=>K.id===G),te=m.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},E=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},P=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},z=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return f==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=k.filter(G=>h.some(Z=>Z.id===G.id)),q=L||O,U=D||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Gt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(nt,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Pt,{value:l,onChange:u}),e.jsx(zt,{selectedUsers:h,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:ke}),e.jsx(_t,{usersToRemove:m,allUsers:k,onRemove:F}),e.jsx(Vt,{usersToUpdate:p,allUsers:k,onRemove:P,getRoleOptions:ke}),e.jsx(qt,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ke,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:E,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Ht,{currentUser:n,currentShare:V,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:z,onRemoveAccess:Y,allUsersToUpdate:f==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||f==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:f==="allTenantUsers"?g:x}:null,allUsersToRemove:f==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||f==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(nt,{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 Kt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),i=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),l=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}),[t,a,n,r,o,i,c,l,d]),h=M.useMemo(()=>p=>s.validateShareData(p),[]),m=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!i)return!1}else if(a==="specificTenantUsers")return i?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,i]);return{buildShareData:u,validateShareData:h,isCurrentStateValid:m,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}};function ct({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:i,onClose:c,shareTabType:l,currentAllUsersShare:d,onRemoveAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Kt(),R=n||r||o,T=()=>{var L,D,O,A;if(R)return"Updating...";if(l==="specific_users"){if(h.length===0&&m.length===0&&p.length===0)return"Select users to share with";const I=h.length+m.length+p.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&m.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(l==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(l==="specific_tenant_users"){if(h.length===0&&m.length===0&&p.length===0)return"Select users to share with";const I=h.length+m.length+p.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&m.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||l==="all_tenant_users"&&!f||l==="specific_tenant_users"&&!f?!0:!C,N=()=>{const L=j();L&&b(L)&&i(L)},k=()=>{var L,D,O,A;if(l==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&i(I)}else{const I=d.role;if(g===I)u==null||u();else{const E=j();if(E&&b(E)){const F={...E,updateAccess:!0};i(F)}}}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&i(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const P={...F,updateAccess:!0};i(P)}}}}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&i(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const P={...F,updateAccess:!0};i(P)}}}}},w=()=>{var L,D,O,A;if(l==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(l==="specific_users"||l==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||m.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!R&&T()]})}),(l==="all_users"||l==="all_tenants"||l==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&T()]})]})}function Cr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:i,shareTabType:c,currentAllUsersShare:l}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const m=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:g}=Kt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&h.length===0)return"Select users to share with";const T=d.length+u.length+h.length;return T===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${T} user${T!==1?"s":""}`:u.length>0&&d.length===0&&h.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&u.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(c==="all_users"){if(!l||l.role==="NONE")return"Share with All Users";const T=l.role;return m===T?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const T=p();T&&f(T)&&o(T)},C=()=>{if(!l||l.role==="NONE"){const T=p();T&&f(T)&&o(T)}else{const T=l.role;if(m===T){const N=p();if(N&&f(N)){const k={...N,removeAccess:!0};o(k)}}else{const N=p();if(N&&f(N)){const k={...N,updateAccess:!0};o(k)}}}},R=()=>!l||l.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:i,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Qt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:i,onShare:c,onRemoveAccess:l}){var N,k,w,L;const{currentUser:d}=os(),[u,h]=M.useState("specific_users"),[m,p]=M.useState("specific_users"),f=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(k=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return m;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=M.useCallback(()=>{f.resetShareState(),i()},[f,i]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,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($e,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:D=>{const O=D;f.setSelectedTab(O),f.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(Nr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(lt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>h(D),isSharing:n,isUpdating:o,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(lt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>h(D),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(ct,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:l}):e.jsx(ct,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:l}):e.jsx(Cr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:l})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Wt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:i,existingShares:c,resetUserSelections:l}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));o(m,{onSuccess:()=>{l()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(p=>{var g,x;const f=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}h&&h.length>0&&h.forEach(m=>{const p=me(n,r,[{scope:"specific_org_user",orgUserId:m.id,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h,tenantId:m}=t;if(u&&u.length>0){const p=Ce(n,r,u.map(f=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,tenantId:m,role:(g==null?void 0:g.role)||"VIEWER"}}));i(p,{onSuccess:()=>{l()}})}if(h&&h.length>0&&h.forEach(p=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:m,role:p.newRole}]);o(f,{onSuccess:()=>{l()}})}),d&&d.length>0){const p=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,tenantId:m,role:f.role})));o(p,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);i(d,{onSuccess:()=>{l()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));o(m,{onSuccess:()=>{l()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(p=>{var g,x;const f=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}h&&h.length>0&&h.forEach(m=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:m.id,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})})}break}}function Jt(t,a,n,r){var u,h,m,p,f,g;const{resourceType:o,resourceId:i,removeMutation:c,existingShares:l,resetUserSelections:d}=r;if(i)if(t.length>0){const x=Ce(o,i,t.map(v=>{var b,C;const j=(C=(b=l==null?void 0:l.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(h=(u=l==null?void 0:l.shares)==null?void 0:u.allTenantsOnly)==null?void 0:h[0];if(j){const b=Ce(o,i,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(p=(m=l==null?void 0:l.shares)==null?void 0:m.tenantWide)==null?void 0:p[0];if(j){const b=Ce(o,i,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(f=l==null?void 0:l.shares)==null?void 0:f.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,i,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function Sr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:l}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:l,resetUserSelections:d};Wt(m,p)},[t,a,n,l,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:l,resetUserSelections:d};Jt(o,i||"",c||"",m)},[t,a,n,l,d,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function wr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:l}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:l,resetUserSelections:d};Wt(m,p)},[t,a,n,l,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:l,resetUserSelections:d};Jt(o,i||"",c||"",m)},[t,a,n,l,d,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Yt(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let i=t.length;if(o!==-1&&(i=o),r!==-1&&r<i&&(i=r),a!==-1){const c=t.substring(0,a),l=t.substring(a);return`${c} {{ filters | where }} AND ${l.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),l=t.substring(n);return`${c} {{ filters | where }} ${l}`}else{const c=t.substring(0,i),l=t.substring(i);return console.log("beforeClause",c),console.log("afterClause",l),l?`${c} {{ filters | where }} ${l}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Bs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const l=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(l,{method:"HEAD"})).ok)throw new Error(`Module not found at ${l}`)}catch{}const d=await import(l);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const l=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",l),o(l),n(null)}})()},[t]),a}function Xt(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const i=r.split("__")[0],c=t.find(l=>l.tabTitle===i);return c?c.id:t[0].id}return a}}return t[0].id}async function dt(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const i=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const l=await c.json();return n.setQueryData(r,l),s.ue.dismiss(i),{data:l,fromCache:!1}}catch(c){throw s.ue.dismiss(i),c}}function Dr(t,a,n,r,o){const i=t.frameObject;a(i);const c=i.cards.find(l=>l.id===i.activeCardId);c&&n(c),r(!0),o(!0)}function kr(){var p;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(f=>f.frame),n=s.useEditorStore(f=>f.card),r=Bs(((p=n.customCardPreferences)==null?void 0:p.url)||""),o=s.useEditorStore(f=>f.selectedSchemaName),i=s.useEditorStore(f=>f.selectedDatamodelId),c=s.useEditorStore(f=>f.selectedDatabaseName),l=s.useEditorStore(f=>f.selectedTableName),d=s.useEditorStore(f=>f.selectedConnectionId),u=s.useEditorStore(f=>f.isShowingVisual),h=n.sql;return{getUpdatedFrame:M.useCallback(()=>{var j;let f=h;h&&!h.includes("{{")&&(f=Yt(h),t(f));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:i,lastSelectedDatabase:c,lastSelectedTable:l,connectionId:d,type:u?n.type:"table",sql:f,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Xt(v,a.activeCardId)}},[n,a,u,o,i,c,l,d,t,r,h])}}function Zt(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:i}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:l,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:h}=s.useDashboardActions(),m=s.useDashboardStore(x=>x.selectedSheetId),p=rr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await dt((t==null?void 0:t.accessToken)||"",x.id,a);return Dr(v,o,i,c,l),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,i,c,l]),g=M.useCallback(async x=>{try{if(r(x),!m)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await dt((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(m,C,"end"),c(!0),d(C.id),h(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,m,u,c,d,h]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:g,getUpdatedFrame:kr().getUpdatedFrame,refetch:p.refetch}}function Tr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,i]=M.useState(""),[c,l]=M.useState(""),[d,u]=M.useState(!1),[h,m]=M.useState(null),[p,f]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:T}=Zt(),{resources:S,isLoading:N,isError:k,createResource:w,updateResource:L,deleteResource:D,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:E,isSharing:F,isRemovingShares:P,isUpdatingShares:_}=ir(()=>{f(!1),x(null)},()=>{r(!1),i(""),l("")}),{handleShareSubmit:z,handleRemoveAccess:Y}=wr((h==null?void 0:h.id)||null,A,E);os();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),f(!0)},U=()=>{g&&D(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=Bt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{T(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{m(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ot,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),i(""),l("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(as,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(cr,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(Qt,{resource:h,resourceType:ee.VISUAL,onShare:z,isSharing:F,isRemoving:P,isUpdating:_,onClose:()=>{u(!1),m(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(f(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Er({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:i,onUpdateDashboard:c,onDeleteClick:l,onDuplicateDashboard:d,onShareDashboard:u,formatDate:h,onDashboardItemClick:m}){var T;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(St,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{p(t),i(t.id),m==null||m(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&f,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&f,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),l(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.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 Ir({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 Ar(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[i,c]=M.useState(""),[l,d]=M.useState(""),[u,h]=M.useState(!1),[m,p]=M.useState(null),[f,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:T,isLoading:S,isError:N,createResource:k,updateResource:w,deleteResource:L,duplicateResource:D,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:E,shareResource:F,removeResourceShares:P}=or(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:z}=Sr((m==null?void 0:m.id)||null,F,P),{currentUser:Y}=os(),W=T.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{i.trim()&&k({title:i,description:l,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),D(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=Bt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=T.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{p(K),Y==null||Y.type,h(!0)};return we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ot,{}):N?e.jsx(Ir,{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:i,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:l,onChange:K=>d(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!i.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:K=>n(K.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ca,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(Er,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&m&&e.jsx(Qt,{resource:m,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:E,onClose:()=>{h(!1),p(null)},onRemoveAccess:z}),e.jsx(s.AlertDialog,{open:f,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function en({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(f=>f.dashboard);const{setDashboard:o,addSheet:i}=s.useDashboardStore(f=>f.actions),{currentUser:c}=os(),l=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),h=Ut(a,{enabled:t}),m=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:h,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:l&&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:l.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:l.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:l.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:l.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.email}),l.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(l.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",l.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ar,{onLoadDashboard:m,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Tr,{})})]})})]})})}function Mr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(E=>E.theme);const n=s.useDashboardStore(E=>E.lenses),r=s.useDashboardStore(E=>E.selectedLensId),o=n==null?void 0:n.find(E=>E.id===r),i=s.useDashboardStore(E=>E.dashboard);s.useDashboardStore(E=>E.selectedSheetId);const c=s.useDashboardStore(E=>E.isDashboardEditing),l=s.useEditorStore(E=>E.card),d=s.useEditorStore(E=>E.selectedConnectionId),[u,h]=M.useState(!1),m=s.useDashboardStore(E=>E.isDashboardPanelOpen),p=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(E=>E.filterValues),g=s.useDashboardStore(E=>E.isVisualEditing),x=s.useDashboardStore(E=>E.showFilters);s.useDashboardStore(E=>E.showDashboardJSON);const v=s.useDashboardStore(E=>E.onSaveFunction),j=s.useDashboardStore(E=>E.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(E=>E.actions),{getSelectedSheet:R,setIsDashboardEditing:T,setShowDashboardJSON:S}=s.useDashboardStore(E=>E.actions),N=R(),{tenantId:k,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>k||w,[k,w]),D=()=>{if(!c||!N)return;const E={dataSource:l.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[E],activeCardId:E.id};b(N.id,F),C(F.id)},O=()=>{T(!0)};async function A(){if(h(!0),!r||!o)return;const E=Os(i),F=JSON.stringify(E),P={...o,template:F,filterValues:f};await vs(P,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(E),h(!1)}if(g)return null;const I=(o==null?void 0:o.name)||i.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(ha,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Pa,{}),!g&&e.jsx(Rt,{}),c&&!g&&L&&e.jsx(Ba,{}),!g&&L&&e.jsx(Fa,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:D,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{T(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(Dt,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(en,{isOpen:m,onClose:()=>p(!1)})]})]})}function Lr({name:t,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:l,icon:d,showNone:u=!1}){const h=ue.useRef(null),[m,p]=ue.useState(!1),[f,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{h.current&&g(h.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":i?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),p(!1)}return e.jsxs(s.Popover,{open:m,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":m,className:s.cn("flex h-9 w-full justify-between",l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:f},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(wt,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function Pe({title:t,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:l=!1,className:d,disabled:u=!1,type:h="combobox"}){const m=r?"Loading...":o?"Error":n;function p(){if(t==="Connection")return e.jsx(wa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ca,{className:"size-4"});if(t==="Table")return e.jsx(rs,{className:"size-4"});if(t==="Model")return e.jsx(Qn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:u,value:m,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(wt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[l&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:m,children:m})]})})]})}function g(){return e.jsx(Lr,{icon:p(),items:a,value:m,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:t,showNone:l})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?f():g()})})}function Rr({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),i=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),l=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),m=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,v){var R;const j=s.createSqlGenConfig(x,l,v),b=(R=d==null?void 0:d.find(T=>T.id===c))==null?void 0:R.name;h(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,i||"");C&&(m(C),p(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Fs({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(As,{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(Et,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Wn,{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 us({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Fs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Or({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=s.useDraggable({id:t,data:{type:n}}),l=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:l,...o,...r,children:a})}function Br({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.groupByColumns}),o=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.metricColumns}),i=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.filterColumns});function c(h){return l(h)||d(h)||u(h)}function l(h){return r==null?void 0:r.some(m=>m.name===h.column_name)}function d(h){return o==null?void 0:o.some(m=>m.name===h.column_name)}function u(h){return i==null?void 0:i.some(m=>m.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(us,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(us,{column:a})}),e.jsx(Or,{id:a.column_name,type:"column",children:e.jsx(us,{column:a})})]})}const ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"groupby",type:"string"},xs={id:"__placeholder__",role:"metric",type:"number"},ps={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},sn={id:"__placeholder__"},Te="droppable-group-by",Ee="droppable-metrics",Ie="droppable-pivot-by",Xe="sortable-group-by",bs="sortable-metrics",Ze="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",Ps="sortable-order-by";function Fr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),i=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:l,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:h,setPreviewPivotColumns:m}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:E}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&E){const P=E.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const z=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===P)){const $=a.findIndex(U=>U.id===P);c($);const q=a.filter(U=>U.id!==ms.id);q.splice($,0,ms),d(q)}else if(E.id===Te){c(a.length);const $=[...a,ms];d($),u(n),h(r)}}if(Y||W){if(i.some($=>$.id===P)){const $=i.findIndex(U=>U.id===P);c($);const q=i.filter(U=>U.id!==hs.id);q.splice($,0,hs),m(q)}else if(E.id===Ie){c(i.length);const $=[...i,hs];m($),d(a),u(n),h(r)}}if(z||Y){if(n.some($=>$.id===P)){console.log("isOverMetricSortable",P);const $=n.findIndex(U=>U.id===P);c($);const q=n.filter(U=>U.id!==xs.id);q.splice($,0,xs),u(q)}else if(E.id===Ee){c(n.length);const $=[...n,xs];u($),h(r),d(a),m(i)}}if(S(_)){if(r.some($=>$.id===P)){const $=r.findIndex(U=>U.id===P);c($);const q=r.filter(U=>U.id!==ps.id);q.splice($,0,ps),h(q)}else if(E.id===Ns){c(r.length);const $=[...r,ps];h($),u(n),d(a),m(i)}}}else d(a),u(n),h(r),m(i)};function T(I){l(I.active.id),c(null),d(a),u(n),h(r),m(i)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:E,data_type:F}=I,P=[...n],_=t!==null?t:n.length,z={...I,id:pe(E),name:E,label:qe(E,y),type:F,role:"metric",aggregate:y};P.splice(_,0,z),f(P)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...i],F=t!==null?t:i.length;let P;y?P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:ze(I.column_name,"month"),granularity:"month"},E.splice(F,0,P),v(E)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...a],F=t!==null?t:a.length;let P;y?P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:ze(I.column_name,"month"),granularity:"month"},E.splice(F,0,P),p(E)}function L(I){const y=[...r],E=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(E,0,F),g(y)}function D(I){var P,_,z,Y,W,V,$,q;const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&E){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(E.id===Te||((P=E.data.current)==null?void 0:P.type)===Xe)&&w(U),(Q||G)&&(E.id===Ie||((_=E.data.current)==null?void 0:_.type)===Ze)?k(U):(H||Q)&&(E.id===Ee||((z=E.data.current)==null?void 0:z.type)===bs)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(E.id===Ns||((Y=E.data.current)==null?void 0:Y.type)===Cs)&&L(U)}if(E&&((W=E.data.current)==null?void 0:W.type)===Xe&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(E&&((V=E.data.current)==null?void 0:V.type)===Ze&&i.some(U=>U.id===y.id)){const U=i.findIndex(Q=>Q.id===y.id),H=i.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...i],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(E&&(($=E.data.current)==null?void 0:$.type)===bs&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(E&&((q=E.data.current)==null?void 0:q.type)===Cs&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),l(null),c(null),d(a),u(n),h(r),m(i)}function O(I){const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)===Ps&&E){const P=o.findIndex(z=>Ve(z.columnId)===y.id),_=o.findIndex(z=>Ve(z.columnId)===E.id);if(P!==-1&&_!==-1&&P!==_){const z=[...o],[Y]=z.splice(P,1);z.splice(_,0,Y),x(z)}}}function A(){l(null),c(null),d(a),u(n),h(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:T,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function qe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ps}-${t}`}function ze(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pr({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),i=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),l=s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),m=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:T,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function k(y){var E;if(i){const F=s.createSqlGenConfig(y,o);C(F);const P=(E=S==null?void 0:S.find(z=>z.id===m))==null?void 0:E.name,_=s.getSql(F,s.fmt(t),s.fmt(a),P||"",T,d||"");_&&(j(_),b(!0))}if(!i){if(s.isTextDataType(y.data_type))if(l&&l.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:qe(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:ze(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:qe(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||N)&&c?(f({connectionId:c,connectionType:T==="S3"||T==="API"?"DuckDb":T||"",databaseName:d||"",schemaName:u||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:T||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:T,databaseName:d||""});R(!1);const E=T==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(E),b(!0)}function D(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:T,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===N)))!==void 0}function A(y){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:E=>E.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Rr,{column:y})})]}):e.jsx(Br,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ja,{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(kt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,E)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},E))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function tn({ColumnsComponent:t,type:a}){var De;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),i=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),l=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:h,setIsDevMode:m,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:T,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:D,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:E,refetchDatabases:F,refetchModels:P,refetchSchemas:_,refetchTables:z,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Pr,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":D?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(p(Z.userSql),setTimeout(()=>{te()},100)):p(""),m(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:F,showNone:!0,onChange:$,isError:k,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!E&&(!c||c==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:i||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(Pe,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:l||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&l)&&(le=!0),le)}return ne()?e.jsx(Pe,{refetch:z,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(Pe,{refetch:W,items:f,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:T,type:"combobox",connectionTooltip:((De=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:De.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ba,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function nn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=M.useState(!1),c=M.useRef(null),l=M.useRef(!1);function d(){t&&!l.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const f=p.toString();navigator.clipboard.writeText(f),i(!0),l.current=!0,setTimeout(()=>{i(!1),l.current=!1},1e3)}else l.current=!1}function m(){i(!1),l.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:h,onMouseDown:m,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function an({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=s.useEditorActions();function l(){o(!r),i(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(nn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:l,variant:"secondary",size:"sm",children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(ma,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function rn({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Nt,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(an,{sql:t,error:a,onDebugWithAssistant:n})})]})}var on={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ut=M.createContext&&M.createContext(on),zr=["attr","size","title"];function _r(t,a){if(t==null)return{};var n=Vr(t,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Vr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function es(){return es=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},es.apply(this,arguments)}function mt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function ss(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?mt(Object(n),!0).forEach(function(r){Ur(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):mt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ur(t,a,n){return a=$r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $r(t){var a=qr(t,"string");return typeof a=="symbol"?a:a+""}function qr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function ln(t){return t&&t.map((a,n)=>M.createElement(a.tag,ss({key:n},a.attr),ln(a.child)))}function Me(t){return a=>M.createElement(Gr,es({attr:ss({},t.attr)},a),ln(t.child))}function Gr(t){var a=n=>{var{attr:r,size:o,title:i}=t,c=_r(t,zr),l=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",es({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:ss(ss({color:t.color||n.color},n.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),i&&M.createElement("title",null,i),t.children)};return ut!==void 0?M.createElement(ut.Consumer,null,n=>a(n)):a(on)}function Hr(t){return Me({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function cn(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),i=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:l}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),h=M.useRef(),m=M.useRef({}),p=r.cards.find(x=>x.id===i),f=M.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);M.useEffect(()=>{if(i&&o.id&&o.id!==i){if(h.current&&c){const x=h.current.getModel();x&&(m.current[o.id]=x);let v=m.current[i];if(!v){const j=f();v=c.editor.createModel(j,t),m.current[i]=v}h.current.setModel(v)}d(i,o),u(!0)}},[i,o,d,c,u,t,f]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=h.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return l(),!1})},[c,l,o]);function g(x,v){if(h.current=x,!m.current[o.id]){const j=x.getModel(),b=f();m.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(m.current[o.id])}return{handleEditorDidMount:g}}function Kr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=cn("sql");function i(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:i,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Qr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=cn("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Wr({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 zs({variant:t="outline"}){var g;const{setCardSql:a}=s.useEditorActions(),n=s.useEditorStore(x=>x.frame),r=s.useEditorStore(x=>x.card),o=Bs(((g=r.customCardPreferences)==null?void 0:g.url)||""),i=s.useEditorStore(x=>x.selectedSchemaName),c=s.useEditorStore(x=>x.selectedDatamodelId),l=s.useEditorStore(x=>x.selectedDatabaseName),d=s.useEditorStore(x=>x.selectedTableName),u=s.useEditorStore(x=>x.selectedConnectionId),h=s.useEditorStore(x=>x.isShowingVisual),m=r.sql,p=s.useEditorStore(x=>x.onSave);function f(){var R;let x=m;m&&!m.includes("{{")&&(x=Yt(m),a(x));const v=(R=o==null?void 0:o.getState())==null?void 0:R.settings,j={...r,dataSource:r.dataSource||{mode:"directSource"},lastSelectedSchema:i,lastSelectedDatamodelId:c,lastSelectedDatabase:l,lastSelectedTable:d,connectionId:u,type:h?r.type:"table",sql:x,customCfg:h?r.customCfg:null,...v&&{customCardPreferences:{...r.customCardPreferences,settings:v}}},b=n.cards.map(T=>T.id===r.id?j:T),C={...n,cards:b,activeCardId:Xt(b,n.activeCardId)};p==null||p(C)}return e.jsxs(s.Button,{onClick:f,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Jr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:i}=Zt(),c=s.useSelectedVisual(),l=lr(),d=()=>{const u=i();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),l.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function _s(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),i=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(i);function l(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:i}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:l,setCardPython:d,setCardCustomCfg:u,setCardPreferences:h,updateDataSource:m,clearQueryConfig:p,setCardConfig:f,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(i);r!=null&&r.queryData||t({queryKey:i,queryData:v}),a.setQueryData(i,null),a.removeQueries({queryKey:i,exact:!0}),n&&m(s.EMPTY_DATA_SOURCE),c(""),l({}),p(),f(void 0),d(""),u(""),h({}),g("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Yr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(z=>z.frame);const i=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const l=s.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.sql}),d=s.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:m,setCardSql:p,setTempQueryData:f,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const R=s.useEditorStore(z=>z.runSql),T=s.useEditorStore(z=>z.actions.setRunSql),S=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:N,isLoading:k,isFetching:w,isSuccess:L,isError:D,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(i);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:z}=s.getKeys(N.records);m(z)}},[N,m,g]),M.useEffect(()=>{(k||w)&&S(!0),(D||L)&&S(!1),D&&(m([]),g(""))},[k,w,N,g,D,L,S,m,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),T(!1))},[R,I,T,A,t]);async function E(){const z=`Can you help me debug this query in the current table scope?
|
|
406
|
+
*/const je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Os(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>It(c))}})}})}}function It(t){return{...t,customCfg:La(t.customCfg),data:[]}}function La(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ra(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function vs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function Oa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Ba(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[l,d]=M.useState(!1),[u,h]=M.useState(!1),m=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function g(){d(!0);const x=Os(m),v=await Ra(t,x,p,f==null?void 0:f.accessToken);v&&(i([...o||[],v]),c(v.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:h,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:l,children:l?"Creating...":"Add"})})]})]})}function Fa(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:o,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function l(h){i(h)}async function d(h){if(await Oa(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==h);o(p||[]),i("original")}}async function u(h){const m=n==null?void 0:n.map(g=>g.id===h.id?{...g,isDefault:!h.isDefault}:{...g,isDefault:!1});o(m||[]);const p={...h,isDefault:!h.isDefault};await vs(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(g=>g.isDefault);if(f&&f.id!==h.id){const g={...f,isDefault:!1};await vs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(da,{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:l,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:m=>{m.preventDefault(),u(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:m=>{m.preventDefault(),d(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function At(){var i;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(i=s.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Mt(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=At();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const l=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(l,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,m=document.createElement("a");m.href=h;const p=`${o}-${new Date().toISOString()}.pdf`;m.download=p,m.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function Pa({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Mt()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:l=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),l&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const rt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Lt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=za(),[l,d]=M.useState(""),[u,h]=M.useState(rt[0].value),[m,p]=M.useState("06:00"),[f,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:l,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:f,onChange:x=>{g(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:rt,value:u,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:m,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:l,frequency:u,time:m,subject:f}),p("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!l,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(bt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(ot,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Xn,{className:"size-3.5"})}),e.jsx(ot,{tooltip:`${x.endUserEmail}`,children:e.jsx(ya,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const ot=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function za(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,i]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),l=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",m={dashboardId:l,endUserId:u},{data:p,isLoading:f,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",l,u],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",m),enabled:!!(c!=null&&c.accessToken)&&!!l&&!!u});async function j({email:C,subject:R,frequency:T,time:S}){const{authToken:N,...k}=At(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:T,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:l,dashboardParams:k};a("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(D,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";i(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{i(null)},2e3)}catch(T){console.error(T),i(null),a("error"),r(T.message)}}return{data:p,isLoading:f,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function os(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:i}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const l=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!l.ok)throw new Error("Failed to fetch user info");return(await l.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:i}}function Rt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const _a=async(t,a,n,r,o,i)=>{const c={},l={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${l[a]}`,t,c)},Va=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Ua=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},i=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!i.ok){const c=await i.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${i.status}`)}return i.json()},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const i=await o.json();throw new Error((i==null?void 0:i.error)||`HTTP error! status: ${o.status}`)}return o.json()},qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},Ga=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Ha=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},i=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!i.ok){const c=await i.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${i.status}`)}return i.json()},Ka=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},Qa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Wa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ja(t,a,n,r,o){const{authToken:i}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>_a((i==null?void 0:i.accessToken)||"",t),enabled:!!(i!=null&&i.accessToken)})}function Ya(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Va((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Xa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Ua((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Za(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>$a((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function er(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>qa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function sr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ga((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function tr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ha((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function nr(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ka((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function ar(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>Qa((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function rr(t,a){return ar(ee.VISUAL,t,a)}function Ot(){const[t,a]=M.useState(new Map),n=M.useCallback((i,c)=>{a(l=>{const d=new Map(l),u=new Set(d.get(i)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(i,u),d})},[]),r=M.useCallback((i,c)=>{a(l=>{const d=new Map(l),u=new Set(d.get(i)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(i):d.set(i,u),d})},[]),o=M.useCallback((i,c)=>{const l=t.get(i);return l?c?l.has(c):l.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Bt(t,a,n){var m;const r=Ja(t),o=Ya(t,n),i=Xa(t),c=Za(t,a),l=er(t),d=sr(),u=tr(),h={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((m=r.data)==null?void 0:m[h[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:i.mutate,deleteResource:c.mutate,duplicateResource:l.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:i.isPending,isDeleting:c.isPending,isDuplicating:l.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function or(t,a){return Bt(ee.DASHBOARD,t,a)}function ir(t,a){return Bt(ee.VISUAL,t,a)}function lr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function cr({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:i,onEditVisual:c,onUpdateVisual:l,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:h,formatDate:m}){var T;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ct,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{p(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>l==null?void 0:l(t.id,{title:S}),isEditable:t.ownership.isOwner&&f,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>l==null?void 0:l(t.id,{description:S}),isEditable:t.ownership.isOwner&&f,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),i(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(Sa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),h(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function Ft({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Ye({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:i=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,l=n.filter(u=>u.value!==t);return i?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:i}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:l.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Pt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(i=>n(i.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(i=>{const c=t.find(d=>d.id===i.id),l=o(i.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[i.name,e.jsx(Ye,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(i.id,d),roleOptions:l}),e.jsx("button",{onClick:()=>n(i.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id)})}),e.jsx(s.Separator,{})]})}function zt({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function _t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),i=l=>{const d=a.find(u=>u.id===l);return(d==null?void 0:d.name)||"Unknown User"},c=l=>{const d=o.find(u=>u.value===l);return(d==null?void 0:d.label)||l};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(l=>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:i(l.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(l.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(l.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(l.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id))})]})}function Vt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const i=c=>{const l=c.target;o.current&&o.current.contains(l)||l instanceof Element&&(l.closest("[data-radix-popper-content-wrapper]")||l.closest("[data-radix-select-content]")||l.closest("[data-radix-popover-content]")||l.closest("[data-radix-dropdown-menu-content]")||l.closest("[data-radix-tooltip-content]")||l.closest('[role="listbox"]')||l.closest('[role="option"]')||l.closest('[role="combobox"]'))||l instanceof Element&&l.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,i),()=>{document.removeEventListener(r,i)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function dr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ur(t,a,n){const r=Ut(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(l=>l.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(l=>l.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(l=>l.tenantUserId===t.id)}function mr({user:t}){return Ut(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 hr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:i}){if(!(a!=null&&a.role))return null;const c=dr((r==null?void 0:r.type)||""),l=n.some(m=>m.id===t.id),d=n.find(m=>m.id===t.id),u=d?d.newRole:a==null?void 0:a.role,h=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Ye,{currentRole:u,onRoleChange:m=>{i(t.id,a.role,m)},roleOptions:h,disabled:!c,allowDropdown:c,className:l?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:xe(u,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function xr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx($e,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function pr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function fr({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,l=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],h=c.orgUsersOnly||[],m=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:[l.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 (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((p,f)=>{var j,b;const g=((j=a.find(C=>C.id===p.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===p.orgUserId))==null?void 0:b.type)||"",v=xe(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},f)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.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((p,f)=>{var j,b;const g=((j=a.find(C=>C.id===p.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===p.tenantUserId))==null?void 0:b.type)||"",v=xe(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},f)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),h.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:h.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),m.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:m.map((p,f)=>{const g=xe(p.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},f)})})]}),!l.length&&!d.length&&!u.length&&!h.length&&!m.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],l=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var f,g;const h=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",p=xe(d.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),l.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:l.map((d,u)=>{const h=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)})})]}),!c.length&&!l.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const i=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:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((l,d)=>{var p,f;const u=((p=a.find(g=>g.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((f=a.find(g=>g.id===l.tenantUserId))==null?void 0:f.type)||"",m=xe(l.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.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((l,d)=>{const u=xe(l.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!i.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function gr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function jr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:i,selectedUser:c,roleOptions:l,currentUser:d,usersToUpdate:u,handleUserToggle:h,handleRemoveAccess:m,handleUpdateAccess:p,handleUserRoleChange:f}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":i?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:i,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?h(t.id):m(t.id):h(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(mr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Ye,{currentRole:a==null?void 0:a.role,onRoleChange:g=>p(t.id,a.role,g),roleOptions:l,disabled:!1,allowDropdown:!0}):e.jsx(hr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>l,handleUpdateAccess:p}),i&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(Ye,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>f(t.id,g),roleOptions:l,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(xr,{hasAccess:r,isUserRemoving:n,isSelected:i,hasAccessFromAPI:o}),e.jsx(pr,{isUserRemoving:n,isSelected:i,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function $t({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:i,handleUserToggle:c,handleUserRoleChange:l,handleRemoveAccess:d,handleUpdateAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(T=>{const S=h.some(k=>k.id===T),N=m.includes(T);S?g.removeSelectedUser(T):N?g.removeUserFromRemove(T):g.addSelectedUser({id:T,role:"VIEWER"})}),v=l||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((T,S,N)=>{g.addUserToUpdate({id:T,currentRole:S,newRole:N})}),C=o,R=m;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(fr,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:i})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(T=>({id:T.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(gr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(T=>{const S=t?ur(T,t,i):void 0,N=R.includes(T.id),k=!!S,w=k&&!N,L=h.some(A=>A.id===T.id),D=h.find(A=>A.id===T.id),O=r(T.type);return e.jsx(jr,{user:T,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:D,roleOptions:O,currentUser:i,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},T.id)})]})]})}function qt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(i=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:i.value,id:i.value,className:"peer sr-only",disabled:i.disabled}),e.jsxs(s.Label,{htmlFor:i.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 ${i.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[i.icon||e.jsx(Se,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:i.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.description})]})]})]},i.value))}),!o&&r.some(i=>i.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 ke=()=>[{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 yr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:i=!1,isUpdating:c=!1,isRemoving:l=!1}){const d=s.useShareCurrentMode(),u=ke().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",m=o?o.newRole:h,p=a.role!=="NONE"&&!i&&(!o||o.newRole===h),f=o!==null&&o.newRole!==h,g=i,x=h==="NONE"||!h,v=b=>{switch(b){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ta,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(h,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",f&&!g&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":g||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),f&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(b=>e.jsxs(s.Button,{variant:m===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||l,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Gt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:i,onRemoveAccess:c,allUsersToUpdate:l,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,m=a?{role:u(a.role)}:{role:"NONE"},p=l?{currentRole:u(l.currentRole),newRole:u(l.newRole)}:null,f=(x,v)=>{i(x,v)},g=()=>{c()};return e.jsx(yr,{currentUser:t,currentShare:m,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:f,onRemoveAccess:g,allUsersToUpdate:p,allUsersToRemove:d})}const vr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function br(t={}){var r,o,i;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>vr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,l)=>l instanceof Error&&l.message.includes("401")||l instanceof Error&&l.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((i=n.data)==null?void 0:i.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:i}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&i?{tenantId:i}:{}}),[a,o,i]),{users:l,isLoading:d,isError:u}=br(c),h=nr(r,n);return{allUsers:l,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function Nr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var W,V;const l=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:h,debouncedSearchQuery:m}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(l==="org")return"organization";if(l==="tenant")return"tenant"},T=()=>{if(l==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:k}=we({debouncedSearchQuery:m,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:T()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),D=S.filter($=>p.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=p.some(Z=>Z.id===$),U=f.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},E=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},P=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const z=k,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(qt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ft,{value:u,onChange:h}),e.jsx(Pt,{selectedUsers:p,selectedUserObjects:D,onRemove:O,onRoleChange:A,getRoleOptions:ke}),e.jsx(zt,{usersToRemove:f,allUsers:L,onRemove:y}),e.jsx(_t,{usersToUpdate:g,allUsers:L,onRemove:E,getRoleOptions:ke}),e.jsx($t,{existingShares:N,isInitialLoading:z,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:ke,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Gt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:F,onRemoveAccess:P,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function it({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var Q;const{searchQuery:l,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=Wa({enabled:(n==null?void 0:n.type)==="organization"}),[R,T]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;T(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:D,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=h.some(K=>K.id===G),te=m.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},E=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},P=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},z=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return f==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=k.filter(G=>h.some(Z=>Z.id===G.id)),q=L||O,U=D||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(qt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(tt,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{value:l,onChange:u}),e.jsx(Pt,{selectedUsers:h,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:ke}),e.jsx(zt,{usersToRemove:m,allUsers:k,onRemove:F}),e.jsx(_t,{usersToUpdate:p,allUsers:k,onRemove:P,getRoleOptions:ke}),e.jsx($t,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ke,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:E,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Gt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:z,onRemoveAccess:Y,allUsersToUpdate:f==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||f==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:f==="allTenantUsers"?g:x}:null,allUsersToRemove:f==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||f==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(tt,{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 Ht=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),i=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),l=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}),[t,a,n,r,o,i,c,l,d]),h=M.useMemo(()=>p=>s.validateShareData(p),[]),m=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!i)return!1}else if(a==="specificTenantUsers")return i?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,i]);return{buildShareData:u,validateShareData:h,isCurrentStateValid:m,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}};function lt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:i,onClose:c,shareTabType:l,currentAllUsersShare:d,onRemoveAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Ht(),R=n||r||o,T=()=>{var L,D,O,A;if(R)return"Updating...";if(l==="specific_users"){if(h.length===0&&m.length===0&&p.length===0)return"Select users to share with";const I=h.length+m.length+p.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&m.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(l==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(l==="specific_tenant_users"){if(h.length===0&&m.length===0&&p.length===0)return"Select users to share with";const I=h.length+m.length+p.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&m.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||l==="all_tenant_users"&&!f||l==="specific_tenant_users"&&!f?!0:!C,N=()=>{const L=j();L&&b(L)&&i(L)},k=()=>{var L,D,O,A;if(l==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&i(I)}else{const I=d.role;if(g===I)u==null||u();else{const E=j();if(E&&b(E)){const F={...E,updateAccess:!0};i(F)}}}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&i(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const P={...F,updateAccess:!0};i(P)}}}}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&i(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const P={...F,updateAccess:!0};i(P)}}}}},w=()=>{var L,D,O,A;if(l==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(l==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(l==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(l==="specific_users"||l==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||m.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!R&&T()]})}),(l==="all_users"||l==="all_tenants"||l==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&T()]})]})}function Cr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:i,shareTabType:c,currentAllUsersShare:l}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const m=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:g}=Ht(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&h.length===0)return"Select users to share with";const T=d.length+u.length+h.length;return T===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${T} user${T!==1?"s":""}`:u.length>0&&d.length===0&&h.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&u.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(c==="all_users"){if(!l||l.role==="NONE")return"Share with All Users";const T=l.role;return m===T?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const T=p();T&&f(T)&&o(T)},C=()=>{if(!l||l.role==="NONE"){const T=p();T&&f(T)&&o(T)}else{const T=l.role;if(m===T){const N=p();if(N&&f(N)){const k={...N,removeAccess:!0};o(k)}}else{const N=p();if(N&&f(N)){const k={...N,updateAccess:!0};o(k)}}}},R=()=>!l||l.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:i,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Kt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:i,onShare:c,onRemoveAccess:l}){var N,k,w,L;const{currentUser:d}=os(),[u,h]=M.useState("specific_users"),[m,p]=M.useState("specific_users"),f=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(k=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return m;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=M.useCallback(()=>{f.resetShareState(),i()},[f,i]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,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($e,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:D=>{const O=D;f.setSelectedTab(O),f.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(Nr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(it,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>h(D),isSharing:n,isUpdating:o,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(it,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>h(D),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(lt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:l}):e.jsx(lt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:l}):e.jsx(Cr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:l})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Qt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:i,existingShares:c,resetUserSelections:l}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));o(m,{onSuccess:()=>{l()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(p=>{var g,x;const f=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}h&&h.length>0&&h.forEach(m=>{const p=me(n,r,[{scope:"specific_org_user",orgUserId:m.id,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h,tenantId:m}=t;if(u&&u.length>0){const p=Ce(n,r,u.map(f=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,tenantId:m,role:(g==null?void 0:g.role)||"VIEWER"}}));i(p,{onSuccess:()=>{l()}})}if(h&&h.length>0&&h.forEach(p=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:m,role:p.newRole}]);o(f,{onSuccess:()=>{l()}})}),d&&d.length>0){const p=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,tenantId:m,role:f.role})));o(p,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);i(d,{onSuccess:()=>{l()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{l()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));o(m,{onSuccess:()=>{l()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(p=>{var g,x;const f=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(f==null?void 0:f.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}h&&h.length>0&&h.forEach(m=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:m.id,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})})}break}}function Wt(t,a,n,r){var u,h,m,p,f,g;const{resourceType:o,resourceId:i,removeMutation:c,existingShares:l,resetUserSelections:d}=r;if(i)if(t.length>0){const x=Ce(o,i,t.map(v=>{var b,C;const j=(C=(b=l==null?void 0:l.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(h=(u=l==null?void 0:l.shares)==null?void 0:u.allTenantsOnly)==null?void 0:h[0];if(j){const b=Ce(o,i,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(p=(m=l==null?void 0:l.shares)==null?void 0:m.tenantWide)==null?void 0:p[0];if(j){const b=Ce(o,i,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(f=l==null?void 0:l.shares)==null?void 0:f.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,i,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function Sr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:l}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:l,resetUserSelections:d};Qt(m,p)},[t,a,n,l,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:l,resetUserSelections:d};Wt(o,i||"",c||"",m)},[t,a,n,l,d,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function wr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:l}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:l,resetUserSelections:d};Qt(m,p)},[t,a,n,l,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:l,resetUserSelections:d};Wt(o,i||"",c||"",m)},[t,a,n,l,d,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Jt(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let i=t.length;if(o!==-1&&(i=o),r!==-1&&r<i&&(i=r),a!==-1){const c=t.substring(0,a),l=t.substring(a);return`${c} {{ filters | where }} AND ${l.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),l=t.substring(n);return`${c} {{ filters | where }} ${l}`}else{const c=t.substring(0,i),l=t.substring(i);return console.log("beforeClause",c),console.log("afterClause",l),l?`${c} {{ filters | where }} ${l}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Bs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const l=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(l,{method:"HEAD"})).ok)throw new Error(`Module not found at ${l}`)}catch{}const d=await import(l);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const l=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",l),o(l),n(null)}})()},[t]),a}function Yt(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const i=r.split("__")[0],c=t.find(l=>l.tabTitle===i);return c?c.id:t[0].id}return a}}return t[0].id}async function ct(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const i=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const l=await c.json();return n.setQueryData(r,l),s.ue.dismiss(i),{data:l,fromCache:!1}}catch(c){throw s.ue.dismiss(i),c}}function Dr(t,a,n,r,o){const i=t.frameObject;a(i);const c=i.cards.find(l=>l.id===i.activeCardId);c&&n(c),r(!0),o(!0)}function kr(){var p;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(f=>f.frame),n=s.useEditorStore(f=>f.card),r=Bs(((p=n.customCardPreferences)==null?void 0:p.url)||""),o=s.useEditorStore(f=>f.selectedSchemaName),i=s.useEditorStore(f=>f.selectedDatamodelId),c=s.useEditorStore(f=>f.selectedDatabaseName),l=s.useEditorStore(f=>f.selectedTableName),d=s.useEditorStore(f=>f.selectedConnectionId),u=s.useEditorStore(f=>f.isShowingVisual),h=n.sql;return{getUpdatedFrame:M.useCallback(()=>{var j;let f=h;h&&!h.includes("{{")&&(f=Jt(h),t(f));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:i,lastSelectedDatabase:c,lastSelectedTable:l,connectionId:d,type:u?n.type:"table",sql:f,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Yt(v,a.activeCardId)}},[n,a,u,o,i,c,l,d,t,r,h])}}function Xt(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:i}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:l,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:h}=s.useDashboardActions(),m=s.useDashboardStore(x=>x.selectedSheetId),p=rr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await ct((t==null?void 0:t.accessToken)||"",x.id,a);return Dr(v,o,i,c,l),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,i,c,l]),g=M.useCallback(async x=>{try{if(r(x),!m)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ct((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(m,C,"end"),c(!0),d(C.id),h(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,m,u,c,d,h]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:g,getUpdatedFrame:kr().getUpdatedFrame,refetch:p.refetch}}function Tr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,i]=M.useState(""),[c,l]=M.useState(""),[d,u]=M.useState(!1),[h,m]=M.useState(null),[p,f]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:T}=Xt(),{resources:S,isLoading:N,isError:k,createResource:w,updateResource:L,deleteResource:D,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:E,isSharing:F,isRemovingShares:P,isUpdatingShares:_}=ir(()=>{f(!1),x(null)},()=>{r(!1),i(""),l("")}),{handleShareSubmit:z,handleRemoveAccess:Y}=wr((h==null?void 0:h.id)||null,A,E);os();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),f(!0)},U=()=>{g&&D(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=Ot(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{T(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{m(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Rt,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),i(""),l("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(as,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(cr,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(Kt,{resource:h,resourceType:ee.VISUAL,onShare:z,isSharing:F,isRemoving:P,isUpdating:_,onClose:()=>{u(!1),m(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(f(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Er({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:i,onUpdateDashboard:c,onDeleteClick:l,onDuplicateDashboard:d,onShareDashboard:u,formatDate:h,onDashboardItemClick:m}){var T;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Ct,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{p(t),i(t.id),m==null||m(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",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&f,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&f,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),l(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.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 Ir({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 Ar(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[i,c]=M.useState(""),[l,d]=M.useState(""),[u,h]=M.useState(!1),[m,p]=M.useState(null),[f,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:T,isLoading:S,isError:N,createResource:k,updateResource:w,deleteResource:L,duplicateResource:D,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:E,shareResource:F,removeResourceShares:P}=or(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:z}=Sr((m==null?void 0:m.id)||null,F,P),{currentUser:Y}=os(),W=T.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{i.trim()&&k({title:i,description:l,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),D(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=Ot(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=T.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{p(K),Y==null||Y.type,h(!0)};return we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Rt,{}):N?e.jsx(Ir,{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:i,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:l,onChange:K=>d(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!i.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:K=>n(K.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ca,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(Er,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&m&&e.jsx(Kt,{resource:m,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:E,onClose:()=>{h(!1),p(null)},onRemoveAccess:z}),e.jsx(s.AlertDialog,{open:f,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(f=>f.dashboard);const{setDashboard:o,addSheet:i}=s.useDashboardStore(f=>f.actions),{currentUser:c}=os(),l=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),h=Vt(a,{enabled:t}),m=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:h,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:l&&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:l.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:l.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:l.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:l.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.email}),l.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(l.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",l.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ar,{onLoadDashboard:m,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Tr,{})})]})})]})})}function Mr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(E=>E.theme);const n=s.useDashboardStore(E=>E.lenses),r=s.useDashboardStore(E=>E.selectedLensId),o=n==null?void 0:n.find(E=>E.id===r),i=s.useDashboardStore(E=>E.dashboard);s.useDashboardStore(E=>E.selectedSheetId);const c=s.useDashboardStore(E=>E.isDashboardEditing),l=s.useEditorStore(E=>E.card),d=s.useEditorStore(E=>E.selectedConnectionId),[u,h]=M.useState(!1),m=s.useDashboardStore(E=>E.isDashboardPanelOpen),p=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(E=>E.filterValues),g=s.useDashboardStore(E=>E.isVisualEditing),x=s.useDashboardStore(E=>E.showFilters);s.useDashboardStore(E=>E.showDashboardJSON);const v=s.useDashboardStore(E=>E.onSaveFunction),j=s.useDashboardStore(E=>E.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(E=>E.actions),{getSelectedSheet:R,setIsDashboardEditing:T,setShowDashboardJSON:S}=s.useDashboardStore(E=>E.actions),N=R(),{tenantId:k,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>k||w,[k,w]),D=()=>{if(!c||!N)return;const E={dataSource:l.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[E],activeCardId:E.id};b(N.id,F),C(F.id)},O=()=>{T(!0)};async function A(){if(h(!0),!r||!o)return;const E=Os(i),F=JSON.stringify(E),P={...o,template:F,filterValues:f};await vs(P,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(E),h(!1)}if(g)return null;const I=(o==null?void 0:o.name)||i.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(ha,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Pa,{}),!g&&e.jsx(Lt,{}),c&&!g&&L&&e.jsx(Ba,{}),!g&&L&&e.jsx(Fa,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:D,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{T(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(wt,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:m,onClose:()=>p(!1)})]})]})}function Lr({name:t,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:l,icon:d,showNone:u=!1}){const h=ue.useRef(null),[m,p]=ue.useState(!1),[f,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{h.current&&g(h.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":i?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),p(!1)}return e.jsxs(s.Popover,{open:m,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":m,className:s.cn("flex h-9 w-full justify-between",l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:f},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(St,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function Pe({title:t,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:l=!1,className:d,disabled:u=!1,type:h="combobox"}){const m=r?"Loading...":o?"Error":n;function p(){if(t==="Connection")return e.jsx(wa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ca,{className:"size-4"});if(t==="Table")return e.jsx(rs,{className:"size-4"});if(t==="Model")return e.jsx(Qn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:u,value:m,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(St,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[l&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:m,children:m})]})})]})}function g(){return e.jsx(Lr,{icon:p(),items:a,value:m,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:t,showNone:l})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?f():g()})})}function Rr({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),i=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),l=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),m=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,v){var R;const j=s.createSqlGenConfig(x,l,v),b=(R=d==null?void 0:d.find(T=>T.id===c))==null?void 0:R.name;h(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,i||"");C&&(m(C),p(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Fs({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(As,{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(Tt,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Wn,{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 us({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Fs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Or({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=s.useDraggable({id:t,data:{type:n}}),l=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:l,...o,...r,children:a})}function Br({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.groupByColumns}),o=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.metricColumns}),i=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.filterColumns});function c(h){return l(h)||d(h)||u(h)}function l(h){return r==null?void 0:r.some(m=>m.name===h.column_name)}function d(h){return o==null?void 0:o.some(m=>m.name===h.column_name)}function u(h){return i==null?void 0:i.some(m=>m.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(us,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(us,{column:a})}),e.jsx(Or,{id:a.column_name,type:"column",children:e.jsx(us,{column:a})})]})}const ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"groupby",type:"string"},xs={id:"__placeholder__",role:"metric",type:"number"},ps={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Te="droppable-group-by",Ee="droppable-metrics",Ie="droppable-pivot-by",Xe="sortable-group-by",bs="sortable-metrics",Ze="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",Ps="sortable-order-by";function Fr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),i=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:l,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:h,setPreviewPivotColumns:m}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:E}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&E){const P=E.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const z=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===P)){const $=a.findIndex(U=>U.id===P);c($);const q=a.filter(U=>U.id!==ms.id);q.splice($,0,ms),d(q)}else if(E.id===Te){c(a.length);const $=[...a,ms];d($),u(n),h(r)}}if(Y||W){if(i.some($=>$.id===P)){const $=i.findIndex(U=>U.id===P);c($);const q=i.filter(U=>U.id!==hs.id);q.splice($,0,hs),m(q)}else if(E.id===Ie){c(i.length);const $=[...i,hs];m($),d(a),u(n),h(r)}}if(z||Y){if(n.some($=>$.id===P)){console.log("isOverMetricSortable",P);const $=n.findIndex(U=>U.id===P);c($);const q=n.filter(U=>U.id!==xs.id);q.splice($,0,xs),u(q)}else if(E.id===Ee){c(n.length);const $=[...n,xs];u($),h(r),d(a),m(i)}}if(S(_)){if(r.some($=>$.id===P)){const $=r.findIndex(U=>U.id===P);c($);const q=r.filter(U=>U.id!==ps.id);q.splice($,0,ps),h(q)}else if(E.id===Ns){c(r.length);const $=[...r,ps];h($),u(n),d(a),m(i)}}}else d(a),u(n),h(r),m(i)};function T(I){l(I.active.id),c(null),d(a),u(n),h(r),m(i)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:E,data_type:F}=I,P=[...n],_=t!==null?t:n.length,z={...I,id:pe(E),name:E,label:qe(E,y),type:F,role:"metric",aggregate:y};P.splice(_,0,z),f(P)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...i],F=t!==null?t:i.length;let P;y?P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:ze(I.column_name,"month"),granularity:"month"},E.splice(F,0,P),v(E)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...a],F=t!==null?t:a.length;let P;y?P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:ze(I.column_name,"month"),granularity:"month"},E.splice(F,0,P),p(E)}function L(I){const y=[...r],E=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(E,0,F),g(y)}function D(I){var P,_,z,Y,W,V,$,q;const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&E){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(E.id===Te||((P=E.data.current)==null?void 0:P.type)===Xe)&&w(U),(Q||G)&&(E.id===Ie||((_=E.data.current)==null?void 0:_.type)===Ze)?k(U):(H||Q)&&(E.id===Ee||((z=E.data.current)==null?void 0:z.type)===bs)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(E.id===Ns||((Y=E.data.current)==null?void 0:Y.type)===Cs)&&L(U)}if(E&&((W=E.data.current)==null?void 0:W.type)===Xe&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(E&&((V=E.data.current)==null?void 0:V.type)===Ze&&i.some(U=>U.id===y.id)){const U=i.findIndex(Q=>Q.id===y.id),H=i.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...i],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(E&&(($=E.data.current)==null?void 0:$.type)===bs&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(E&&((q=E.data.current)==null?void 0:q.type)===Cs&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===E.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),l(null),c(null),d(a),u(n),h(r),m(i)}function O(I){const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)===Ps&&E){const P=o.findIndex(z=>Ve(z.columnId)===y.id),_=o.findIndex(z=>Ve(z.columnId)===E.id);if(P!==-1&&_!==-1&&P!==_){const z=[...o],[Y]=z.splice(P,1);z.splice(_,0,Y),x(z)}}}function A(){l(null),c(null),d(a),u(n),h(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:T,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function qe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ps}-${t}`}function ze(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pr({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),i=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),l=s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),m=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:T,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function k(y){var E;if(i){const F=s.createSqlGenConfig(y,o);C(F);const P=(E=S==null?void 0:S.find(z=>z.id===m))==null?void 0:E.name,_=s.getSql(F,s.fmt(t),s.fmt(a),P||"",T,d||"");_&&(j(_),b(!0))}if(!i){if(s.isTextDataType(y.data_type))if(l&&l.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:qe(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:ze(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:qe(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||N)&&c?(f({connectionId:c,connectionType:T==="S3"||T==="API"?"DuckDb":T||"",databaseName:d||"",schemaName:u||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:T||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:T,databaseName:d||""});R(!1);const E=T==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(E),b(!0)}function D(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:T,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===N)))!==void 0}function A(y){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:E=>E.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Rr,{column:y})})]}):e.jsx(Br,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ja,{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(Dt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,E)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},E))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var De;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),i=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),l=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:h,setIsDevMode:m,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:T,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:D,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:E,refetchDatabases:F,refetchModels:P,refetchSchemas:_,refetchTables:z,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Pr,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":D?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(p(Z.userSql),setTimeout(()=>{te()},100)):p(""),m(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:F,showNone:!0,onChange:$,isError:k,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!E&&(!c||c==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:i||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(Pe,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:l||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&l)&&(le=!0),le)}return ne()?e.jsx(Pe,{refetch:z,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(Pe,{refetch:W,items:f,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:T,type:"combobox",connectionTooltip:((De=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:De.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ba,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=M.useState(!1),c=M.useRef(null),l=M.useRef(!1);function d(){t&&!l.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const f=p.toString();navigator.clipboard.writeText(f),i(!0),l.current=!0,setTimeout(()=>{i(!1),l.current=!1},1e3)}else l.current=!1}function m(){i(!1),l.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:h,onMouseDown:m,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=s.useEditorActions();function l(){o(!r),i(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:l,variant:"secondary",size:"sm",children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(ma,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(bt,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},dt=M.createContext&&M.createContext(rn),zr=["attr","size","title"];function _r(t,a){if(t==null)return{};var n=Vr(t,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Vr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function es(){return es=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},es.apply(this,arguments)}function ut(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function ss(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?ut(Object(n),!0).forEach(function(r){Ur(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ut(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ur(t,a,n){return a=$r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $r(t){var a=qr(t,"string");return typeof a=="symbol"?a:a+""}function qr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function on(t){return t&&t.map((a,n)=>M.createElement(a.tag,ss({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Gr,es({attr:ss({},t.attr)},a),on(t.child))}function Gr(t){var a=n=>{var{attr:r,size:o,title:i}=t,c=_r(t,zr),l=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",es({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:ss(ss({color:t.color||n.color},n.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),i&&M.createElement("title",null,i),t.children)};return dt!==void 0?M.createElement(dt.Consumer,null,n=>a(n)):a(rn)}function Hr(t){return Me({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),i=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:l}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),h=M.useRef(),m=M.useRef({}),p=r.cards.find(x=>x.id===i),f=M.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);M.useEffect(()=>{if(i&&o.id&&o.id!==i){if(h.current&&c){const x=h.current.getModel();x&&(m.current[o.id]=x);let v=m.current[i];if(!v){const j=f();v=c.editor.createModel(j,t),m.current[i]=v}h.current.setModel(v)}d(i,o),u(!0)}},[i,o,d,c,u,t,f]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=h.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return l(),!1})},[c,l,o]);function g(x,v){if(h.current=x,!m.current[o.id]){const j=x.getModel(),b=f();m.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(m.current[o.id])}return{handleEditorDidMount:g}}function Kr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function i(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:i,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Qr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Wr({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 zs({variant:t="outline"}){var g;const{setCardSql:a}=s.useEditorActions(),n=s.useEditorStore(x=>x.frame),r=s.useEditorStore(x=>x.card),o=Bs(((g=r.customCardPreferences)==null?void 0:g.url)||""),i=s.useEditorStore(x=>x.selectedSchemaName),c=s.useEditorStore(x=>x.selectedDatamodelId),l=s.useEditorStore(x=>x.selectedDatabaseName),d=s.useEditorStore(x=>x.selectedTableName),u=s.useEditorStore(x=>x.selectedConnectionId),h=s.useEditorStore(x=>x.isShowingVisual),m=r.sql,p=s.useEditorStore(x=>x.onSave);function f(){var R;let x=m;m&&!m.includes("{{")&&(x=Jt(m),a(x));const v=(R=o==null?void 0:o.getState())==null?void 0:R.settings,j={...r,dataSource:r.dataSource||{mode:"directSource"},lastSelectedSchema:i,lastSelectedDatamodelId:c,lastSelectedDatabase:l,lastSelectedTable:d,connectionId:u,type:h?r.type:"table",sql:x,customCfg:h?r.customCfg:null,...v&&{customCardPreferences:{...r.customCardPreferences,settings:v}}},b=n.cards.map(T=>T.id===r.id?j:T),C={...n,cards:b,activeCardId:Yt(b,n.activeCardId)};p==null||p(C)}return e.jsxs(s.Button,{onClick:f,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Jr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:i}=Xt(),c=s.useSelectedVisual(),l=lr(),d=()=>{const u=i();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),l.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function _s(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),i=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(i);function l(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:i}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:l,setCardPython:d,setCardCustomCfg:u,setCardPreferences:h,updateDataSource:m,clearQueryConfig:p,setCardConfig:f,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(i);r!=null&&r.queryData||t({queryKey:i,queryData:v}),a.setQueryData(i,null),a.removeQueries({queryKey:i,exact:!0}),n&&m(s.EMPTY_DATA_SOURCE),c(""),l({}),p(),f(void 0),d(""),u(""),h({}),g("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Yr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(z=>z.frame);const i=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const l=s.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.sql}),d=s.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:m,setCardSql:p,setTempQueryData:f,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const R=s.useEditorStore(z=>z.runSql),T=s.useEditorStore(z=>z.actions.setRunSql),S=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:N,isLoading:k,isFetching:w,isSuccess:L,isError:D,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(i);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:z}=s.getKeys(N.records);m(z)}},[N,m,g]),M.useEffect(()=>{(k||w)&&S(!0),(D||L)&&S(!1),D&&(m([]),g(""))},[k,w,N,g,D,L,S,m,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),T(!1))},[R,I,T,A,t]);async function E(){const z=`Can you help me debug this query in the current table scope?
|
|
407
407
|
|
|
408
408
|
Error:
|
|
409
409
|
|
|
@@ -415,11 +415,11 @@
|
|
|
415
415
|
|
|
416
416
|
${d?`Python:
|
|
417
417
|
${d}`:""}
|
|
418
|
-
`;b(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Wr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function 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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Kr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Qr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(rn,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:E}),e.jsx(is,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(Hr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{}),e.jsx(zs,{})]})]})}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(),F()]}),_()]})}function Xr({data:t}){var c;const[a,n]=M.useState([]),o=Object.keys(t[0]).map(l=>({accessorKey:l,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[l,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(l=>e.jsx(s.TableRow,{className:"",children:l.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))},l.id))}),e.jsx(s.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(l=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":l.getIsSelected()&&"selected",children:l.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},l.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Zr({card:t}){var b,C,R,T,S,N,k,w,L,D,O;const[a,n]=M.useState(!1),[r,o]=M.useState([]),{authToken:i}=s.useSemaphorContext(),c=s.getTokenParams(i==null?void 0:i.accessToken),l=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(b=l==null?void 0:l.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((T=t.customCardPreferences)==null?void 0:T.url)||""),h=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",m=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),g=M.useCallback((A,I)=>{o(y=>({...y,[A]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=u((k=t.customCardPreferences)==null?void 0:k.componentName);function v(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var E,F,P;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(P=m==null?void 0:m.cards)==null?void 0:P.find(_=>_.id===I);return y||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(f==null?void 0:f.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((D=t.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(A=>{var E,F,P;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(P=m==null?void 0:m.cards)==null?void 0:P.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function dn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,i=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:l}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===i.filterId),{data:u,isLoading:h,isFetching:m,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:f}=s.useEditorActions(),{data:g}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(Zr,{card:C})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!m)return p?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||m?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>f({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>f({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>l({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const fs=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),eo=()=>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."})]})]}),so=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{language:"javascript",value:t,onChange:o})})]}),to=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function no(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[o,i]=M.useState(""),[c,l]=M.useState(""),[d,u]=M.useState(""),h=s.useEditorStore(T=>T.card),m=s.useEditorStore(T=>T.card.customCfg),p=m?JSON.stringify(m,null,2):"",{data:f}=s.useDashboardCardQuery(h),{data:g}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=T=>{var S,N;return JSON.stringify({...T,data:{...T.data,datasets:(N=(S=T.data)==null?void 0:S.datasets)==null?void 0:N.map(k=>({...k,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=f==null?void 0:f.records)!=null&&S.length))return;const T=s.createChartConfig({card:h,data:f.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:g});if(T){r(j(T)),l(((N=h.preferences)==null?void 0:N.customVisualCode)||"");const k=s.merge(T,m);i(j(k))}},C=()=>{try{if(c&&v(c),o){const T=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),T);x(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(eo,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(dn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(so,{customCode:c,cardCustomCfgString:p,mergedConfig:o,onConfigChange:T=>i(T??""),onCodeChange:T=>l(T??"")})]}),e.jsx(to,{error:d,hasCardCustomConfig:!!m,onReset:()=>{i(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function ls(t){const[a,n]=M.useState(null);return a}function Vs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function ao({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=s.useEditorActions(),{data:l}=Vs();function d(u,h){r(null),o({}),i(u),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(l){const p=(await Promise.all((h=l==null?void 0:l.plugins)==null?void 0:h.map(async f=>(await s.loadManifest(f.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:f.value}))))).flat();n(p)}})()},[l]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((u,h)=>e.jsx(ro,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+h))})]})}const ro=({text:t,icon:a,onClick:n})=>{const r=ls(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function Us(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function oo(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function $s(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function qs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Gs(t){return Me({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Hs(t){return Me({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function un({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function d(h,m){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),l(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(ns,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(Es,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx($s,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(as,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Us,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(vt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ue,{className:s.cn("size-5",a)})})]})}function io({chartType:t,className:a,customIcon:n,componentName:r}){const o=ls();switch(t){case"bar":return e.jsx(ts,{className:a});case"line":return e.jsx(ns,{className:a});case"pie":return e.jsx(as,{className:a});case"radar":return e.jsx(Ls,{className:a});case"scatter":return e.jsx(Es,{className:a});case"bubble":return e.jsx($s,{className:a});case"doughnut":return e.jsx(Is,{className:a});case"stackedBar":return e.jsx(ks,{className:a});case"stackedLine":return e.jsx(Gs,{className:a});case"polarArea":return e.jsx(Us,{className:a});case"funnel":return e.jsx(qs,{className:a});case"tornado":case"pyramid":return e.jsx(Rs,{className:a});case"range":return e.jsx(Ts,{className:a});case"kpi":return e.jsx(Hs,{className:a});case"text":return e.jsx(It,{className:a});case"map":return e.jsx(Ms,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ue,{className:a});default:return e.jsx(rs,{className:a})}}function mn({variant:t="ghost"}){var i,c;const[a,n]=M.useState(!1),r=s.useEditorStore(l=>l.card),o=r.type;return s.useDashboardStore(l=>l.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(io,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:l=>l.preventDefault(),className:"w-72 p-1",children:[e.jsx(un,{onChartTypeChange:()=>n(!1)}),e.jsx(ao,{onChartTypeChange:()=>n(!1)})]})]})}const Ge="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function ht(t,a){var r,o,i;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function lo(){var E,F,P,_,z,Y;const[t,a]=M.useState(!1),n=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.preferences}),r=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.type}),o=s.getNumberAxis(n,{}),[i,c]=M.useState(ht(n,r)),[l,d]=M.useState(((P=(F=(E=n==null?void 0:n.chartOptions)==null?void 0:E.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[u,h]=M.useState(((Y=(z=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:z[o])==null?void 0:Y.max)||""),[m,p]=M.useState(l||u?"custom":"auto"),[f,g]=M.useState(""),[x,v]=M.useState(0),[j,b]=M.useState(""),[C,R]=M.useState(""),[T,S]=M.useState(""),N=s.useEditorStore(W=>W.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(W=>W.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var W,V,$,q,U,H,Q,G,Z,te,ae,se,oe,K;c(ht(n,r)),d((($=(V=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:V[o])==null?void 0:$.min)===0?0:""),h(((H=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:H.max)||""),g(((te=(Z=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,o,r]);function D(W,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(W)}function O(){const W=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>R(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),W.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:T,onValueChange:V=>S(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>v(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ge}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:i,onValueChange:W=>c(W),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:m,onValueChange:W=>p(W),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),m==="custom"&&i=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:l,onChange:W=>d(V=>D(V,W.target.value)),className:`col-span-1 h-8 w-full ${Ge}`}),e.jsx(s.Input,{value:u,onChange:W=>h(V=>D(V,W.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ge}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:f,onChange:W=>g(V=>D(V,W.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ge}`})]})]})}function y(){var q;let W={};m==="custom"&&(W={min:l,max:u,ticks:{stepSize:f}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:i,...i==="linear"?W:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:T}};console.log(V),N(V);const $={...w,preferences:V};k($)}return e.jsxs(s.Popover,{onOpenChange:W=>a(W),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(na,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function co(){const t=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.position}),a=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.align}),n=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.display}),{setLegendOptions:r}=s.useEditorActions(),o=l=>{r({display:l,position:t,align:a})},i=l=>{r({display:n,position:l,align:a})},c=l=>{r({display:n,position:t,align:l})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(xa,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Un,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx($n,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(Fn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Bn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Pn,{className:"size-4"})})]})]})]})]})]})})]})}function uo(){const t=s.useEditorStore(i=>{var c,l;return(l=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:l.indexAxis}),a=s.useEditorStore(i=>i.card.type),{setChartOrientation:n}=s.useEditorStore(i=>i.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(rt,{className:"size-4"}):e.jsx(at,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(rt,{className:"size-4"}):e.jsx(at,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function hn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(uo,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(lo,{}),e.jsx(co,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(ua,{className:"size-4"}),r==="x"&&e.jsx(ea,{className:"size-4"}),r==="y"&&e.jsx(Da,{className:"size-4"}),r==="none"&&e.jsx(Aa,{className:"size-4"})]})]}):null}function mo(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=s.useEditorActions(),c=(g,x)=>{g.dataTransfer.setData("tabIndex",x.toString())},l=g=>{g.preventDefault()},d=(g,x)=>{const v=g.dataTransfer.getData("tabIndex");if(v===x.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(x,0,b),n({...t,cards:j})};function u(g){const x=t.cards.filter(b=>b.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function h(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function m(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,g)}function p(g){const x={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(g,x)}function f(g,x){return g.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||g.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:v}),i({...x,displayTab:v})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(aa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((g,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,x),onDragOver:l,onDrop:v=>d(v,x),className:"",value:g.id,children:[f(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),i({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:m,children:e.jsx(ta,{className:"h-4 w-4"})})]})})}function xn(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:l,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:h,isFetching:m}=s.useDashboardCardQuery(a);function p(x){const v=t.cards.find(j=>j.id===x);if(v!=null&&v.sql){r||l(!0),i(x);return}if(v!=null&&v.queryConfig){r&&l(!1),f(x),i(x);return}r||f(x),i(x)}function f(x){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};o(v);const j=v.cards.find(b=>b.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(dn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:g()},x.id)),e.jsx(mo,{})]})}function He({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:l,setActiveTabCardId:d,runAssistant:u,setIsDevMode:h}=s.useEditorActions(),{data:m,isLoading:p,isFetching:f,errorMessage:g}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(m==null?void 0:m.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),T=document.createElement("a");T.href=R,T.download=`${a.title}.json`,T.click()}function v(){const C=[Object.keys(m==null?void 0:m.records.reduce((N,k)=>({...N,...k}),{})).join(","),...((m==null?void 0:m.records)||[]).map(N=>Object.values(N).join(","))].join(`
|
|
419
|
-
`),R=new Blob([C],{type:"text/csv"}),T=URL.createObjectURL(R),S=document.createElement("a");S.href=T,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||f)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(mn,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Kn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(no,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(oo,{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(oa,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(hn,{})]}),n&&e.jsx(xo,{})]}),r?e.jsx(xn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(ho,{})}),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:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(Xr,{data:(m==null?void 0:m.records)||[]}),g&&e.jsx(nn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ho(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function po(){var x,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=Vs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:l,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function h(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function m(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(T=>{var S;return((S=T==null?void 0:T.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((T,S)=>{var N,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:T}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((k=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:k.cardId)||"",onValueChange:w=>h(S,w)})]},S+Math.random())})})}function p(j,b,C=[],R=""){var T,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((T=t==null?void 0:t.settings)==null?void 0:T[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function f(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),p(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(Hn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:g,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:l&&e.jsx(he,{icon:e.jsx(sa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.filter(j=>j.type===i).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:m(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(u)})})]})]})]})}function Le(){const[t,a]=M.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),i=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var h;return(h=u.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(u,h){var m,p;h?n!=null&&n.onClickFilter&&((m=n==null?void 0:n.onClickFilter)==null?void 0:m.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(f=>f.columnIndex!==u)}),a(f=>{const g=[...f];return g[u]=!1,g}))}function l(u,h){var p;const m=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===u?{...f,expression:h.target.value}:f);o({...n,onClickFilter:m})}function d(u){var h,m,p,f;if(t!=null&&t[u]||(m=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))!=null&&m.expression)return e.jsx(s.Input,{value:(f=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))==null?void 0:f.expression,onChange:g=>l(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),i==null?void 0:i.map((u,h)=>{var m,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((m=n==null?void 0:n.onClickFilter)!=null&&m.find(f=>f.columnIndex===h)),onCheckedChange:f=>c(h,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const g=[...f];return g[h]=!f[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},u)})]})}function fo({idx:t}){var l;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(l=a==null?void 0:a.chartOptions)==null?void 0:l.indexAxis,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:h}]});else{const m={...i};m.datalabels=h;const p=n==null?void 0:n.map(f=>f.idx===u?m:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Tt,{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(pa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ga,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(fa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function go(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ks({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function pn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,h,m;return(m=(h=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:m.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:l}=go();return l.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:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:fn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(gn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function fn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function gn({col:t,idx:a,className:n,iconClassName:r,children:o}){const i=s.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),c=s.useEditorStore(h=>{var m,p;return(p=(m=h.card)==null?void 0:m.preferences)==null?void 0:p.datasetOptions}),l=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function u(h){if(!l)d({...i,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const m={...l};m.type=h==="area"?"line":h,m.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?m:f);d({...i,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ks,{className:"max-w-[100px]",title:t,children:fn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ns,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(bt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fo,{idx:a})]})]})}function jn(){const t=s.useEditorStore(f=>f.selectedConnectionId),a=s.useEditorStore(f=>f.selectedDatamodelId),n=s.useEditorStore(f=>f.selectedDatabaseName),r=s.useEditorStore(f=>f.selectedSchemaName),o=s.useEditorStore(f=>f.selectedTableName),i=s.useDashboardStore(f=>f.dashboard.filters)||[],c=s.useDashboardStore(f=>f.actions.addFilter),l=s.useDashboardStore(f=>f.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:h,connectionType:m}=s.useEditorAside();function p(f,g="dashboard"){var N;const x=s.fmt(f.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(h);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:m,databaseName:v}),R=`${C}.${x}`;const T=(N=u==null?void 0:u.find(k=>k.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${T}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${T}`);const S=i==null?void 0:i.find(k=>k.column===R&&k.table===b&&(k.database===v||k.database===n));if(S)d(S.id),l(S.id);else{const k=s.v4();return h==="api"&&t?(c({location:g,id:k,column:R,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),k):(c({id:k,location:g,column:R,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),k)}}return{assignFilter:p}}function _e(){const t=s.useDashboardStore(l=>l.dashboard.filters),a=s.useEditorStore(l=>l.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();function i(l){const d=o(l,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(l=>l.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(jo,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jo({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,i]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(l=>l.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(l=>e.jsxs(s.CommandItem,{value:l.column_name,onSelect:d=>{const u=d===o?"":d;i(u),r(!1),u&&a(l)},children:[l.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===l.column_name?"opacity-100":"opacity-0")})]},l.column_name))})]})]})})]})}function yo({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(pn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function cs(){const t=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>l.isDevMode),n=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:r}=s.useEditorStore(l=>l.actions);function o(l){var h;const d={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(u)}function i(){var l,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var l,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function vo({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(cs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}const bo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},No={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Co(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:So(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{}),e.jsx(Le,{}),e.jsx(_e,{})]})]})}function So(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(bo,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(No,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 wo(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function gs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Do=[{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"}],ko=["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"],To=ko.map(t=>({label:t,value:t}));function Eo(){var d,u,h,m,p,f,g,x,v,j,b,C,R,T,S,N,k,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=M.useState(((m=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(L=>({label:L,value:L}))||[],l=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(gs,{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(gs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:l,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Do,value:((x=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:To,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(gs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(T=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var D,O,A,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var D,O,A,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Io(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Ke({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[t!=="text"&&e.jsx(cs,{}),t==="text"&&e.jsx(Io,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Ao(){const t=s.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(pn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Mo({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const Lo=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Ro=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."]})]}),Oo=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 Bo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ao,{});case"tornado":case"pyramid":return e.jsx(Ke,{docContent:Lo,cardType:n});case"kpi":return e.jsx(wo,{});case"line":case"bar":return e.jsx(yo,{cardType:n});case"range":return e.jsx(Ke,{docContent:Ro,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ke,{cardType:n});case"bubble":case"scatter":return e.jsx(vo,{cardType:n});case"table":return e.jsx(Mo,{cardType:n});case"text":return e.jsx(Ke,{docContent:Oo,cardType:n,suffix:"Visual"});case"map":return e.jsx(Eo,{});case"custom":return e.jsx(po,{});default:return e.jsx(Co,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function yn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:t,showPlaceholderLabel:!1})}const Fo=[{label:"Sum",value:"SUM",logo:e.jsx(kt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(As,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(la,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Vn,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Po({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Fo;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...t,aggregate:o,label:qe(t.name,o)};a(t.id,i)}return e.jsx(yn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const zo=[{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 _o({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:ze(t.name,r)};a(t.id,o)}return e.jsx(yn,{column:t,functions:zo,onFunctionChange:r=>n(r),label:"Granularity"})}function Vo({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=M.useMemo(()=>{let l=[];(n===Te||n===Ee||n===Ie)&&(l=r);const d=l==null?void 0:l.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),i=[{id:t.name,value:t.name}];function c(l){const d=r==null?void 0:r.find(u=>{var h;return u.column_name===((h=l[0])==null?void 0:h.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function vn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,h;return(h=(u=d.card)==null?void 0:u.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(gn,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function l(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(cs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&l()]})}function Uo({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:l,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:h,setNodeRef:m,transform:p,transition:f,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(p),transition:f}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":k?"string":w?"date":"string";if(r===Te){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,role:"groupby",label:ze(S.column_name,"month"),granularity:"month"};c(t.id,D)}}if(r===Ie){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,label:ze(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,D)}}if(r===Ee){const D={id:t.id,name:S.column_name,type:L,role:"metric",label:qe(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};l(t.id,D)}}function b(){if(r===Ee)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(vn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Ee)return e.jsx(Po,{column:t});if((r===Te||r===Ie)&&S)return e.jsx(_o,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Te||r===Ie)&&v}),children:e.jsx(Vo,{col:t,onChange:j,droppableId:r})})}function T(){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:()=>i(!o),children:o?e.jsx(Ea,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Ct,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...u,ref:m,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[T(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function js({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var x,v;const{setNodeRef:c,isOver:l,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),h=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),m=l||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,p=u?r:n,f=o===Xe?"Rows":o===Ze?"Pivot Columns":"Columns";function g(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",m&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),g(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(j=>j.id===sn.id?e.jsx($o,{},j.id):e.jsx(Uo,{droppableId:t,type:o,column:j,onRemoveColumn:i},j.id))})]})})}function $o(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function bn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:l,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:l}:void 0;return e.jsx("div",{...o,...r,ref:i,style:u,children:t})}function qo(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const l=e.jsx(Gn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(_n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function p(j,b){const C=f(j);return C?C.role==="metric"?b==="asc"?u:h:b==="asc"?l:d:null}function f(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};i(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>Ve(j.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),m.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:m,selectedOptions:[],onChange:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(bn,{id:Ve(j.columnId),type:Ps,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(Ct,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ks,{className:"w-[175px] text-sm",children:((b=f(j.columnId))==null?void 0:b.label)||((C=f(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:p(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},j.columnId)},Ve(j.columnId))})]})})}function Go(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),i=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:l,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function h(v){l(v)}function m(v){d(v)}function p(v){u(v)}let f="Group By",g="Metrics",x="Stack By";return a==="table"&&(f="Rows",g="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(un,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(js,{onRemoveColumn:h,sortableType:Xe,id:Te,label:f,columns:t,previewColumns:n}),e.jsx(js,{onRemoveColumn:p,sortableType:Ze,id:Ie,label:x,columns:i,previewColumns:c}),e.jsx(js,{onRemoveColumn:m,sortableType:bs,id:Ee,label:g,columns:r,previewColumns:o}),e.jsx(qo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Qs({children:t,column:a,id:n,sortableType:r,className:o}){const[i,c]=M.useState(!1),{removeEditorFilter:l,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(m=>{var p,f;return(f=(p=m.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(g=>g.filterColumnName===a.name)});function h(m){l(m)}return e.jsx(bn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>h(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function Ho({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,T;return(T=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:T.filters}),o=s.useEditorStore(C=>{var R,T;return(T=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:T.find(S=>S.name===t.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:l}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),m={column:t.name,sql:t.sql,id:t.name,connectionId:i,dataType:t.type},{data:p,isLoading:f,isFetching:g,isError:x}=s.useFilterQuery(m),v=M.useMemo(()=>{var R;return m.column?(R=p==null?void 0:p.records)==null?void 0:R.map(T=>{let S=m.column.split(".").slice(-1)[0].replace(/"/g,"");return T[S]===void 0&&(S=S.toLowerCase()),{id:T[S],value:T[S]}}):[]},[p,m.column]);function j(C){const R=C.map(T=>T.id);h(t.name,R)}function b(){return f||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(Ko,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Qs,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function Ko({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(l=>l.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Qo({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=s.useEditorAside(),l={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:h,data:m}=s.useFilterQuery(l),p=m==null?void 0:m.records,{dateRange:f,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const T={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,T)}function b(){v(t.name,null,!0),g(x)}function C(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:l.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Qs,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Wo({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,x;const{setNodeRef:i,isOver:c,over:l}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},h=c||((x=(g=l==null?void 0:l.data)==null?void 0:g.current)==null?void 0:x.type)===o;function m(){if(!f||f.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(v){const j=s.isDateDataType(v.type);return v.id===sn.id?e.jsx(Qs,{id:v.id,sortableType:o,column:v,children:e.jsx(Jo,{})},v.id):j?e.jsx(Qo,{droppableId:t,sortableType:o,column:v},v.id):e.jsx(Ho,{droppableId:t,sortableType:o,column:v},v.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:i,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),m(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(v=>p(v))})]})})}function Jo(){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 Yo(){const t=s.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wo,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:a})})}function Xo(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(is,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(rn,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(_s,{}),e.jsx(zs,{variant:"default"})]})]})}function Zo(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog),o=s.useEditorStore(l=>l.isDevMode);M.useEffect(()=>{var l,d,u,h;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(h=a.current)==null||h.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Yr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Bo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(He,{})})]}):e.jsx(He,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Go,{})})}),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(Xo,{}),e.jsx(Yo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(He,{})})]})})]}):e.jsx(He,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function ei(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[o,i]=M.useState(null),{authToken:c}=s.useSemaphorContext(),l=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.sql}),d=s.useEditorStore(B=>B.isDevMode),u=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.python}),{setCardPython:h,setCardSql:m,setRunSql:p,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],v=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),R=s.useEditorStore(B=>B.selectedTableName),T=s.useEditorStore(B=>B.selectedConnectionId),S=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:D,setCurrentAssitantScope:O,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:E}=s.useEditorAside(),{messages:F,setMessages:P,reload:_,error:z,append:Y,input:W,setInput:V,status:$,handleInputChange:q,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:Q,onFinish(B,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&v&&(Y({role:"user",content:v}),D(!1))},[j,v,Y,D]);async function Q({toolCall:B}){var J,ie,ye,De;if(["createChartFromSql","createForecast"].includes(B.toolName)){const ne=B.args.sql,le=B.args.python,ce=B.args.chartType;return f(ce),m(ne),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return l?{status:"success",sql:l,python:u||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const ne=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,f(ne),A(le),m(void 0),h(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(ye=ce==null?void 0:ce.data)!=null&&ye.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(De=ce==null?void 0:ce.data)==null?void 0:De.records}}else r("Analyzing...")}}function G(B){i(J=>J?{promptTokens:J.promptTokens+B.promptTokens,completionTokens:J.completionTokens+B.completionTokens,totalTokens:J.totalTokens+B.totalTokens}:B)}function Z(B){const J=s.removeFromScopeArray(x,B);te(J)}function te(B){const J=s.sanitizeAIScope(B);O(J),P(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:T||"",connectionType:y||""},J=s.dedup([...x,B]);te(J)}function se(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:T||"",connectionType:y||"",datamodelId:E||""};if(!s.isInAiScopeArray([...N||[],...x],B)||x.length===0){const ie=s.dedup([...N||[],...x,B]).filter(ye=>ye.connectionId===B.connectionId);te(ie)}}const oe=!["ready","error"].includes($),K=s.getErrorMessage(z);return{messages:F,setMessages:P,reload:_,append:Y,input:W,setInput:V,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:H,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:K}}const si=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function xt(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[o,i]=M.useState(s.isDevEnv),[c,l]=M.useState(!1),[d,u]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),f=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),v=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:T}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:k,append:w,input:L,setInput:D,isLoading:O,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:E,llmUsage:F,errorMessage:P}=ei();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),M.useEffect(()=>{var H;v&&((H=a.current)==null||H.focus(),m({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[v,f,m]);function _(H,Q){Q==="sql"?(g(H),x(!0)):Q==="python"&&(C(H),x(!0))}function z(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],u(!0)}function Y(){h.selectedEntities.length===0&&m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function W(H){Y();const Q={role:"user",content:H.title+" "+H.subtitle};w(Q)}function V(H){Y(),w({role:"user",content:H})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:l,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:z,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:E,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!T&&e.jsx(s.Placeholders,{onClick:W,placeholders:si}),e.jsx("div",{children:U&&T&&e.jsx(s.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:D,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Y(),I(H)},isLoading:O,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:d,onOpenChange:u,dataSource:f||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Nn(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Cn(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function ti(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function Ss(t,a){const n=Nn(a,t),r=s.getDataType(t.dataType),o=r==="date",i={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",l=Cn(t.label,c);return{...i,role:"metric",label:l,aggregate:c}}return a==="groupBy"?{...i,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...i,role:"pivotby"}:a==="sortBy"?{...i,role:"sortby",label:t.label,direction:"asc"}:null}function Sn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const i=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return i===t&&c===a||i===a&&c===t})}function ni(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Sn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ws(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Ds(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Ws=t=>{var D;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:l,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),h=s.useEditorStore(O=>O.card.type),m=t==null?void 0:t.id,p=M.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),f=M.useCallback((O,A)=>{if(m)switch(O){case"groupBy":{a(m,{groupByColumns:A});break}case"metrics":{a(m,{metricColumns:A});break}case"pivotBy":{a(m,{pivotByColumns:A});break}case"sortBy":{a(m,{sortByColumns:A});break}}},[m,a]),g=M.useCallback((O,A,I)=>{if(!m)return;const E=p(O)[A];if(E)switch(O){case"groupBy":n(m,E.id,{label:I});break;case"metrics":r(m,E.id,{label:I});break;case"pivotBy":o(m,E.id,{label:I});break;case"sortBy":i(m,E.id,{label:I});break}},[m,p,n,r,o,i]),x=M.useCallback((O,A)=>{if(!m)return;const y=p("metrics")[O];y&&r(m,y.id,{aggregate:A,label:Cn(y.name,A)})},[m,p,r]),v=M.useCallback((O,A,I)=>{if(!m)return;const E=p("groupBy")[O];if(!E)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(m,E.id,F)},[m,p,n]),j=M.useCallback((O,A)=>{if(!m)return;const y=p("groupBy")[O];y&&n(m,y.id,{granularity:A})},[m,p,n]),b=M.useCallback((O,A)=>{if(!m)return;const y=p("metrics")[O];y&&r(m,y.id,{aliasTemplate:A})},[m,p,r]),C=M.useCallback((O,A)=>{if(console.log("handleValueAliasesChange",O,A),!m)return;console.log("handleValueAliasesChange",O,A);const y=p("metrics")[O];y&&(console.log("handleValueAliasesChange",A),r(m,y.id,{valueAliases:A}))},[m,p,r]),R=M.useCallback(O=>{m&&a(m,{comparisonType:O})},[m,a]),T=M.useCallback(O=>{m&&a(m,{showTrendline:O})},[m,a]),S=M.useCallback(O=>{m&&a(m,{trendlineWindow:O})},[m,a]),N=M.useCallback(O=>{m&&a(m,{trendlineGranularity:O})},[m,a]),k=M.useCallback(O=>{m&&a(m,{targetValue:O})},[m,a]),w=M.useCallback(O=>{var _;if(!m)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=ni(O,A,I);if(!y.isValid){y.showError&&ws();return}const E=ti(O),F=p(E);if(Ds(O,F))return;const P=Ss(O,E);P&&f(E,[...F,P])},[m,(D=t==null?void 0:t.config)==null?void 0:D.joinPlan,p,f]),L=M.useCallback((O,A)=>{if(!m)return;const y=p(O)[A];if(y){if(O!=="sortBy"){const E=p("sortBy"),F=E.filter(P=>!(P.name===y.name&&P.qualifiedEntityName===y.qualifiedEntityName));F.length!==E.length&&a(m,{sortByColumns:F})}switch(O){case"groupBy":c(m,y.id);break;case"metrics":l(m,y.id);break;case"pivotBy":d(m,y.id);break;case"sortBy":u(m,y.id);break}}},[m,p,c,l,d,u,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:T,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:k,cardType:h}};function ai({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=s.useSortable({id:t.id}),[l,d]=M.useState(!1),u=s.useEditorStore(x=>x.card),{handleFieldClick:h}=Ws(u),m={transform:s.CSS.Transform.toString(o),transition:i},p=s.getDataType(t.dataType),g=(x=>{const v=(x||"").toLowerCase();switch(s.getDataType(v)){case"number":return As;case"date":return s.Calendar;case"boolean":return Et;case"json":return Zn;case"geo":return va;default:return It}})(t.dataType);return e.jsxs("div",{ref:r,style:m,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(g,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),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/90 hover:text-foreground dark:text-muted-foreground ${l?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),l&&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(Tt,{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(Ma,{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 ri(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:l,error:d}=s.useColumns(),u=i.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},p=(n==="all"?u:u.filter(C=>h(C)===n)).reduce((C,R)=>{const T=R.qualifiedEntityName||"Other Fields";return C[T]||(C[T]={label:s.toLabel(R.entityName),fields:[]}),C[T].fields.push(R),C},{}),g=Object.keys(p),x=u.filter(C=>h(C)==="dimensions").length,v=u.filter(C=>h(C)==="metrics").length,j=u.filter(C=>h(C)==="calculated").length,b=u.length>0;return l?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[i.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Jn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(p).map(([C,R])=>{const T=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 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:T.label||T.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(ai,{field:S},S.id))})})]},C)})}),Object.keys(p).length===0&&i.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&i.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 oi(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ri,{})," "]})}function ii({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[o,i]=M.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,N={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,N]}),i(new Set([...o,N.id]))},l=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),i(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var D,O;const k=n.joins.find(A=>A.id===S);if(!k)return;const w={...k,...N},L=n.joins.map(A=>A.id===S?w:A);if((D=w.source)!=null&&D.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var P;return F.name===((P=w.source)==null?void 0:P.name)}),I=a.find(F=>{var P;return F.name===((P=w.target)==null?void 0:P.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},E=[...w.joinKeyGroups];E[0]={...E[0],keys:[y]},w.joinKeyGroups=E,L[L.findIndex(F=>F.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:l,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N>0){const k=[...n.joins],w={...k[N]},L={...k[N-1]};k[N]=L,k[N-1]=w,k.forEach((O,A)=>{O.sequence=A+1});const D={...n,joins:k};r(D)}},moveJoinDown:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N<n.joins.length-1){const k=[...n.joins],w={...k[N]},L={...k[N+1]};k[N]=L,k[N+1]=w,k.forEach((O,A)=>{O.sequence=A+1});const D={...n,joins:k};r(D)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),i(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const k=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:k},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const k=n.joins.find(L=>L.id===S);if(!k)return;const w=[...k.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const k=n.joins.find(A=>A.id===S);if(!k)return;const w=a.find(A=>A.name===k.source.name),L=a.find(A=>A.name===k.target.name),D=[...k.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};D[N]={...D[N],keys:[...D[N].keys,O]},d(S,{joinKeyGroups:D})},updateJoinKey:(S,N,k,w,L)=>{const D=n.joins.find(E=>E.id===S);if(!D)return;const O=a.find(E=>E.name===D.source.name),A=a.find(E=>E.name===D.target.name),I=[...D.joinKeyGroups],y=I[N].keys[k];w==="sourceColumnName"&&O?I[N].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[N].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[k]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(k,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
|
|
418
|
+
`;b(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Wr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function 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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Kr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Qr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(an,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:E}),e.jsx(is,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(Hr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{}),e.jsx(zs,{})]})]})}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(),F()]}),_()]})}function Xr({data:t}){var c;const[a,n]=M.useState([]),o=Object.keys(t[0]).map(l=>({accessorKey:l,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[l,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(l=>e.jsx(s.TableRow,{className:"",children:l.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))},l.id))}),e.jsx(s.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(l=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":l.getIsSelected()&&"selected",children:l.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},l.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Zr({card:t}){var b,C,R,T,S,N,k,w,L,D,O;const[a,n]=M.useState(!1),[r,o]=M.useState([]),{authToken:i}=s.useSemaphorContext(),c=s.getTokenParams(i==null?void 0:i.accessToken),l=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(b=l==null?void 0:l.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((T=t.customCardPreferences)==null?void 0:T.url)||""),h=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",m=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),g=M.useCallback((A,I)=>{o(y=>({...y,[A]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=u((k=t.customCardPreferences)==null?void 0:k.componentName);function v(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var E,F,P;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(P=m==null?void 0:m.cards)==null?void 0:P.find(_=>_.id===I);return y||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(f==null?void 0:f.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((D=t.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(A=>{var E,F,P;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(P=m==null?void 0:m.cards)==null?void 0:P.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function cn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,i=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:l}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===i.filterId),{data:u,isLoading:h,isFetching:m,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:f}=s.useEditorActions(),{data:g}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(Zr,{card:C})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!m)return p?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||m?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>f({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>f({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>l({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const fs=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),eo=()=>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."})]})]}),so=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{language:"javascript",value:t,onChange:o})})]}),to=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function no(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[o,i]=M.useState(""),[c,l]=M.useState(""),[d,u]=M.useState(""),h=s.useEditorStore(T=>T.card),m=s.useEditorStore(T=>T.card.customCfg),p=m?JSON.stringify(m,null,2):"",{data:f}=s.useDashboardCardQuery(h),{data:g}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=T=>{var S,N;return JSON.stringify({...T,data:{...T.data,datasets:(N=(S=T.data)==null?void 0:S.datasets)==null?void 0:N.map(k=>({...k,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=f==null?void 0:f.records)!=null&&S.length))return;const T=s.createChartConfig({card:h,data:f.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:g});if(T){r(j(T)),l(((N=h.preferences)==null?void 0:N.customVisualCode)||"");const k=s.merge(T,m);i(j(k))}},C=()=>{try{if(c&&v(c),o){const T=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),T);x(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(eo,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(so,{customCode:c,cardCustomCfgString:p,mergedConfig:o,onConfigChange:T=>i(T??""),onCodeChange:T=>l(T??"")})]}),e.jsx(to,{error:d,hasCardCustomConfig:!!m,onReset:()=>{i(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function ls(t){const[a,n]=M.useState(null);return a}function Vs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function ao({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=s.useEditorActions(),{data:l}=Vs();function d(u,h){r(null),o({}),i(u),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(l){const p=(await Promise.all((h=l==null?void 0:l.plugins)==null?void 0:h.map(async f=>(await s.loadManifest(f.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:f.value}))))).flat();n(p)}})()},[l]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((u,h)=>e.jsx(ro,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+h))})]})}const ro=({text:t,icon:a,onClick:n})=>{const r=ls(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function Us(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function oo(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function $s(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function qs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Gs(t){return Me({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Hs(t){return Me({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function dn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function d(h,m){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),l(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(ns,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(Es,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx($s,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(as,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Us,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(yt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ue,{className:s.cn("size-5",a)})})]})}function io({chartType:t,className:a,customIcon:n,componentName:r}){const o=ls();switch(t){case"bar":return e.jsx(ts,{className:a});case"line":return e.jsx(ns,{className:a});case"pie":return e.jsx(as,{className:a});case"radar":return e.jsx(Ls,{className:a});case"scatter":return e.jsx(Es,{className:a});case"bubble":return e.jsx($s,{className:a});case"doughnut":return e.jsx(Is,{className:a});case"stackedBar":return e.jsx(ks,{className:a});case"stackedLine":return e.jsx(Gs,{className:a});case"polarArea":return e.jsx(Us,{className:a});case"funnel":return e.jsx(qs,{className:a});case"tornado":case"pyramid":return e.jsx(Rs,{className:a});case"range":return e.jsx(Ts,{className:a});case"kpi":return e.jsx(Hs,{className:a});case"text":return e.jsx(Et,{className:a});case"map":return e.jsx(Ms,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ue,{className:a});default:return e.jsx(rs,{className:a})}}function un({variant:t="ghost"}){var i,c;const[a,n]=M.useState(!1),r=s.useEditorStore(l=>l.card),o=r.type;return s.useDashboardStore(l=>l.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(io,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:l=>l.preventDefault(),className:"w-72 p-1",children:[e.jsx(dn,{onChartTypeChange:()=>n(!1)}),e.jsx(ao,{onChartTypeChange:()=>n(!1)})]})]})}const Ge="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function mt(t,a){var r,o,i;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function lo(){var E,F,P,_,z,Y;const[t,a]=M.useState(!1),n=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.preferences}),r=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.type}),o=s.getNumberAxis(n,{}),[i,c]=M.useState(mt(n,r)),[l,d]=M.useState(((P=(F=(E=n==null?void 0:n.chartOptions)==null?void 0:E.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[u,h]=M.useState(((Y=(z=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:z[o])==null?void 0:Y.max)||""),[m,p]=M.useState(l||u?"custom":"auto"),[f,g]=M.useState(""),[x,v]=M.useState(0),[j,b]=M.useState(""),[C,R]=M.useState(""),[T,S]=M.useState(""),N=s.useEditorStore(W=>W.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(W=>W.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var W,V,$,q,U,H,Q,G,Z,te,ae,se,oe,K;c(mt(n,r)),d((($=(V=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:V[o])==null?void 0:$.min)===0?0:""),h(((H=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:H.max)||""),g(((te=(Z=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,o,r]);function D(W,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(W)}function O(){const W=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>R(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),W.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:T,onValueChange:V=>S(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>v(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ge}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:i,onValueChange:W=>c(W),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:m,onValueChange:W=>p(W),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),m==="custom"&&i=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:l,onChange:W=>d(V=>D(V,W.target.value)),className:`col-span-1 h-8 w-full ${Ge}`}),e.jsx(s.Input,{value:u,onChange:W=>h(V=>D(V,W.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ge}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:f,onChange:W=>g(V=>D(V,W.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ge}`})]})]})}function y(){var q;let W={};m==="custom"&&(W={min:l,max:u,ticks:{stepSize:f}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:i,...i==="linear"?W:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:T}};console.log(V),N(V);const $={...w,preferences:V};k($)}return e.jsxs(s.Popover,{onOpenChange:W=>a(W),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(na,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function co(){const t=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.position}),a=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.align}),n=s.useEditorStore(l=>{var d,u,h,m;return(m=(h=(u=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.display}),{setLegendOptions:r}=s.useEditorActions(),o=l=>{r({display:l,position:t,align:a})},i=l=>{r({display:n,position:l,align:a})},c=l=>{r({display:n,position:t,align:l})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(xa,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Un,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx($n,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(Fn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Bn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Pn,{className:"size-4"})})]})]})]})]})]})})]})}function uo(){const t=s.useEditorStore(i=>{var c,l;return(l=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:l.indexAxis}),a=s.useEditorStore(i=>i.card.type),{setChartOrientation:n}=s.useEditorStore(i=>i.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(at,{className:"size-4"}):e.jsx(nt,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(at,{className:"size-4"}):e.jsx(nt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function mn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(uo,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(lo,{}),e.jsx(co,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(ua,{className:"size-4"}),r==="x"&&e.jsx(ea,{className:"size-4"}),r==="y"&&e.jsx(Da,{className:"size-4"}),r==="none"&&e.jsx(Aa,{className:"size-4"})]})]}):null}function mo(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=s.useEditorActions(),c=(g,x)=>{g.dataTransfer.setData("tabIndex",x.toString())},l=g=>{g.preventDefault()},d=(g,x)=>{const v=g.dataTransfer.getData("tabIndex");if(v===x.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(x,0,b),n({...t,cards:j})};function u(g){const x=t.cards.filter(b=>b.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function h(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function m(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,g)}function p(g){const x={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(g,x)}function f(g,x){return g.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||g.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:v}),i({...x,displayTab:v})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(aa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((g,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,x),onDragOver:l,onDrop:v=>d(v,x),className:"",value:g.id,children:[f(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),i({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:m,children:e.jsx(ta,{className:"h-4 w-4"})})]})})}function hn(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:l,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:h,isFetching:m}=s.useDashboardCardQuery(a);function p(x){const v=t.cards.find(j=>j.id===x);if(v!=null&&v.sql){r||l(!0),i(x);return}if(v!=null&&v.queryConfig){r&&l(!1),f(x),i(x);return}r||f(x),i(x)}function f(x){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};o(v);const j=v.cards.find(b=>b.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:g()},x.id)),e.jsx(mo,{})]})}function He({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:l,setActiveTabCardId:d,runAssistant:u,setIsDevMode:h}=s.useEditorActions(),{data:m,isLoading:p,isFetching:f,errorMessage:g}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(m==null?void 0:m.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),T=document.createElement("a");T.href=R,T.download=`${a.title}.json`,T.click()}function v(){const C=[Object.keys(m==null?void 0:m.records.reduce((N,k)=>({...N,...k}),{})).join(","),...((m==null?void 0:m.records)||[]).map(N=>Object.values(N).join(","))].join(`
|
|
419
|
+
`),R=new Blob([C],{type:"text/csv"}),T=URL.createObjectURL(R),S=document.createElement("a");S.href=T,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||f)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(un,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Kn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(no,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(oo,{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(oa,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(mn,{})]}),n&&e.jsx(xo,{})]}),r?e.jsx(hn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(ho,{})}),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:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(Xr,{data:(m==null?void 0:m.records)||[]}),g&&e.jsx(tn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ho(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function po(){var x,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=Vs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:l,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function h(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function m(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(T=>{var S;return((S=T==null?void 0:T.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((T,S)=>{var N,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:T}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((k=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:k.cardId)||"",onValueChange:w=>h(S,w)})]},S+Math.random())})})}function p(j,b,C=[],R=""){var T,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((T=t==null?void 0:t.settings)==null?void 0:T[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function f(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),p(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(Hn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:g,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:l&&e.jsx(he,{icon:e.jsx(sa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.filter(j=>j.type===i).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:m(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(u)})})]})]})]})}function Le(){const[t,a]=M.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),i=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var h;return(h=u.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(u,h){var m,p;h?n!=null&&n.onClickFilter&&((m=n==null?void 0:n.onClickFilter)==null?void 0:m.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(f=>f.columnIndex!==u)}),a(f=>{const g=[...f];return g[u]=!1,g}))}function l(u,h){var p;const m=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===u?{...f,expression:h.target.value}:f);o({...n,onClickFilter:m})}function d(u){var h,m,p,f;if(t!=null&&t[u]||(m=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))!=null&&m.expression)return e.jsx(s.Input,{value:(f=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))==null?void 0:f.expression,onChange:g=>l(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),i==null?void 0:i.map((u,h)=>{var m,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((m=n==null?void 0:n.onClickFilter)!=null&&m.find(f=>f.columnIndex===h)),onCheckedChange:f=>c(h,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const g=[...f];return g[h]=!f[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},u)})]})}function fo({idx:t}){var l;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(l=a==null?void 0:a.chartOptions)==null?void 0:l.indexAxis,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:h}]});else{const m={...i};m.datalabels=h;const p=n==null?void 0:n.map(f=>f.idx===u?m:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(kt,{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(pa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ga,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(fa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function go(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ks({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function xn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,h,m;return(m=(h=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:m.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:l}=go();return l.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:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:pn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(fn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function pn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function fn({col:t,idx:a,className:n,iconClassName:r,children:o}){const i=s.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),c=s.useEditorStore(h=>{var m,p;return(p=(m=h.card)==null?void 0:m.preferences)==null?void 0:p.datasetOptions}),l=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function u(h){if(!l)d({...i,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const m={...l};m.type=h==="area"?"line":h,m.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?m:f);d({...i,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ks,{className:"max-w-[100px]",title:t,children:pn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ns,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(vt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fo,{idx:a})]})]})}function gn(){const t=s.useEditorStore(f=>f.selectedConnectionId),a=s.useEditorStore(f=>f.selectedDatamodelId),n=s.useEditorStore(f=>f.selectedDatabaseName),r=s.useEditorStore(f=>f.selectedSchemaName),o=s.useEditorStore(f=>f.selectedTableName),i=s.useDashboardStore(f=>f.dashboard.filters)||[],c=s.useDashboardStore(f=>f.actions.addFilter),l=s.useDashboardStore(f=>f.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:h,connectionType:m}=s.useEditorAside();function p(f,g="dashboard"){var N;const x=s.fmt(f.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(h);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:m,databaseName:v}),R=`${C}.${x}`;const T=(N=u==null?void 0:u.find(k=>k.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${T}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${T}`);const S=i==null?void 0:i.find(k=>k.column===R&&k.table===b&&(k.database===v||k.database===n));if(S)d(S.id),l(S.id);else{const k=s.v4();return h==="api"&&t?(c({location:g,id:k,column:R,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),k):(c({id:k,location:g,column:R,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,C,x)}),k)}}return{assignFilter:p}}function _e(){const t=s.useDashboardStore(l=>l.dashboard.filters),a=s.useEditorStore(l=>l.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();function i(l){const d=o(l,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(l=>l.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(jo,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jo({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,i]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(l=>l.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(l=>e.jsxs(s.CommandItem,{value:l.column_name,onSelect:d=>{const u=d===o?"":d;i(u),r(!1),u&&a(l)},children:[l.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===l.column_name?"opacity-100":"opacity-0")})]},l.column_name))})]})]})})]})}function yo({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(xn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function cs(){const t=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>l.isDevMode),n=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:r}=s.useEditorStore(l=>l.actions);function o(l){var h;const d={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(u)}function i(){var l,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var l,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function vo({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(cs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}const bo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},No={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Co(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:So(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{}),e.jsx(Le,{}),e.jsx(_e,{})]})]})}function So(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(bo,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(No,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 wo(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function gs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Do=[{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"}],ko=["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"],To=ko.map(t=>({label:t,value:t}));function Eo(){var d,u,h,m,p,f,g,x,v,j,b,C,R,T,S,N,k,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=M.useState(((m=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(L=>({label:L,value:L}))||[],l=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(gs,{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(gs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:l,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Do,value:((x=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:To,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(gs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var D;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(T=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var D,O,A,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var D,O,A,I;o({...t.preferences,mapVisualOptions:{...(D=t.preferences)==null?void 0:D.mapVisualOptions,projectionOffset:[((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Io(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Ke({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[t!=="text"&&e.jsx(cs,{}),t==="text"&&e.jsx(Io,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Ao(){const t=s.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(xn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Mo({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const Lo=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Ro=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."]})]}),Oo=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 Bo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ao,{});case"tornado":case"pyramid":return e.jsx(Ke,{docContent:Lo,cardType:n});case"kpi":return e.jsx(wo,{});case"line":case"bar":return e.jsx(yo,{cardType:n});case"range":return e.jsx(Ke,{docContent:Ro,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ke,{cardType:n});case"bubble":case"scatter":return e.jsx(vo,{cardType:n});case"table":return e.jsx(Mo,{cardType:n});case"text":return e.jsx(Ke,{docContent:Oo,cardType:n,suffix:"Visual"});case"map":return e.jsx(Eo,{});case"custom":return e.jsx(po,{});default:return e.jsx(Co,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function jn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:t,showPlaceholderLabel:!1})}const Fo=[{label:"Sum",value:"SUM",logo:e.jsx(Dt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(As,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(la,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Vn,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Po({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Fo;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...t,aggregate:o,label:qe(t.name,o)};a(t.id,i)}return e.jsx(jn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const zo=[{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 _o({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:ze(t.name,r)};a(t.id,o)}return e.jsx(jn,{column:t,functions:zo,onFunctionChange:r=>n(r),label:"Granularity"})}function Vo({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=M.useMemo(()=>{let l=[];(n===Te||n===Ee||n===Ie)&&(l=r);const d=l==null?void 0:l.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),i=[{id:t.name,value:t.name}];function c(l){const d=r==null?void 0:r.find(u=>{var h;return u.column_name===((h=l[0])==null?void 0:h.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function yn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,h;return(h=(u=d.card)==null?void 0:u.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(fn,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function l(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(cs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&l()]})}function Uo({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:l,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:h,setNodeRef:m,transform:p,transition:f,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(p),transition:f}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":k?"string":w?"date":"string";if(r===Te){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,role:"groupby",label:ze(S.column_name,"month"),granularity:"month"};c(t.id,D)}}if(r===Ie){if(k){const D={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,D)}if(w){const D={id:t.id,name:S.column_name,type:L,label:ze(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,D)}}if(r===Ee){const D={id:t.id,name:S.column_name,type:L,role:"metric",label:qe(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};l(t.id,D)}}function b(){if(r===Ee)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(yn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Ee)return e.jsx(Po,{column:t});if((r===Te||r===Ie)&&S)return e.jsx(_o,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Te||r===Ie)&&v}),children:e.jsx(Vo,{col:t,onChange:j,droppableId:r})})}function T(){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:()=>i(!o),children:o?e.jsx(Ea,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Nt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...u,ref:m,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[T(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function js({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var x,v;const{setNodeRef:c,isOver:l,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),h=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),m=l||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,p=u?r:n,f=o===Xe?"Rows":o===Ze?"Pivot Columns":"Columns";function g(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",m&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),g(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(j=>j.id===en.id?e.jsx($o,{},j.id):e.jsx(Uo,{droppableId:t,type:o,column:j,onRemoveColumn:i},j.id))})]})})}function $o(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function vn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:l,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:l}:void 0;return e.jsx("div",{...o,...r,ref:i,style:u,children:t})}function qo(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const l=e.jsx(Gn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(_n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(qn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function p(j,b){const C=f(j);return C?C.role==="metric"?b==="asc"?u:h:b==="asc"?l:d:null}function f(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};i(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>Ve(j.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),m.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:m,selectedOptions:[],onChange:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(vn,{id:Ve(j.columnId),type:Ps,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(Nt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ks,{className:"w-[175px] text-sm",children:((b=f(j.columnId))==null?void 0:b.label)||((C=f(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:p(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},j.columnId)},Ve(j.columnId))})]})})}function Go(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),i=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:l,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function h(v){l(v)}function m(v){d(v)}function p(v){u(v)}let f="Group By",g="Metrics",x="Stack By";return a==="table"&&(f="Rows",g="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(dn,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(js,{onRemoveColumn:h,sortableType:Xe,id:Te,label:f,columns:t,previewColumns:n}),e.jsx(js,{onRemoveColumn:p,sortableType:Ze,id:Ie,label:x,columns:i,previewColumns:c}),e.jsx(js,{onRemoveColumn:m,sortableType:bs,id:Ee,label:g,columns:r,previewColumns:o}),e.jsx(qo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Qs({children:t,column:a,id:n,sortableType:r,className:o}){const[i,c]=M.useState(!1),{removeEditorFilter:l,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(m=>{var p,f;return(f=(p=m.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(g=>g.filterColumnName===a.name)});function h(m){l(m)}return e.jsx(vn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>h(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function Ho({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,T;return(T=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:T.filters}),o=s.useEditorStore(C=>{var R,T;return(T=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:T.find(S=>S.name===t.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:l}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),m={column:t.name,sql:t.sql,id:t.name,connectionId:i,dataType:t.type},{data:p,isLoading:f,isFetching:g,isError:x}=s.useFilterQuery(m),v=M.useMemo(()=>{var R;return m.column?(R=p==null?void 0:p.records)==null?void 0:R.map(T=>{let S=m.column.split(".").slice(-1)[0].replace(/"/g,"");return T[S]===void 0&&(S=S.toLowerCase()),{id:T[S],value:T[S]}}):[]},[p,m.column]);function j(C){const R=C.map(T=>T.id);h(t.name,R)}function b(){return f||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(Ko,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Qs,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function Ko({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(l=>l.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Qo({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=s.useEditorAside(),l={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:h,data:m}=s.useFilterQuery(l),p=m==null?void 0:m.records,{dateRange:f,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const T={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,T)}function b(){v(t.name,null,!0),g(x)}function C(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:l.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Qs,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Wo({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,x;const{setNodeRef:i,isOver:c,over:l}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},h=c||((x=(g=l==null?void 0:l.data)==null?void 0:g.current)==null?void 0:x.type)===o;function m(){if(!f||f.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(v){const j=s.isDateDataType(v.type);return v.id===en.id?e.jsx(Qs,{id:v.id,sortableType:o,column:v,children:e.jsx(Jo,{})},v.id):j?e.jsx(Qo,{droppableId:t,sortableType:o,column:v},v.id):e.jsx(Ho,{droppableId:t,sortableType:o,column:v},v.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:i,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),m(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(v=>p(v))})]})})}function Jo(){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 Yo(){const t=s.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wo,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:a})})}function Xo(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(is,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(an,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(_s,{}),e.jsx(zs,{variant:"default"})]})]})}function Zo(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog),o=s.useEditorStore(l=>l.isDevMode);M.useEffect(()=>{var l,d,u,h;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(h=a.current)==null||h.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Yr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Bo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(He,{})})]}):e.jsx(He,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Go,{})})}),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(Xo,{}),e.jsx(Yo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(He,{})})]})})]}):e.jsx(He,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function ei(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[o,i]=M.useState(null),{authToken:c}=s.useSemaphorContext(),l=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.sql}),d=s.useEditorStore(B=>B.isDevMode),u=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.python}),{setCardPython:h,setCardSql:m,setRunSql:p,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],v=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),R=s.useEditorStore(B=>B.selectedTableName),T=s.useEditorStore(B=>B.selectedConnectionId),S=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:D,setCurrentAssitantScope:O,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:E}=s.useEditorAside(),{messages:F,setMessages:P,reload:_,error:z,append:Y,input:W,setInput:V,status:$,handleInputChange:q,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:Q,onFinish(B,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&v&&(Y({role:"user",content:v}),D(!1))},[j,v,Y,D]);async function Q({toolCall:B}){var J,ie,ye,De;if(["createChartFromSql","createForecast"].includes(B.toolName)){const ne=B.args.sql,le=B.args.python,ce=B.args.chartType;return f(ce),m(ne),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return l?{status:"success",sql:l,python:u||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const ne=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,f(ne),A(le),m(void 0),h(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(ye=ce==null?void 0:ce.data)!=null&&ye.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(De=ce==null?void 0:ce.data)==null?void 0:De.records}}else r("Analyzing...")}}function G(B){i(J=>J?{promptTokens:J.promptTokens+B.promptTokens,completionTokens:J.completionTokens+B.completionTokens,totalTokens:J.totalTokens+B.totalTokens}:B)}function Z(B){const J=s.removeFromScopeArray(x,B);te(J)}function te(B){const J=s.sanitizeAIScope(B);O(J),P(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:T||"",connectionType:y||""},J=s.dedup([...x,B]);te(J)}function se(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:T||"",connectionType:y||"",datamodelId:E||""};if(!s.isInAiScopeArray([...N||[],...x],B)||x.length===0){const ie=s.dedup([...N||[],...x,B]).filter(ye=>ye.connectionId===B.connectionId);te(ie)}}const oe=!["ready","error"].includes($),K=s.getErrorMessage(z);return{messages:F,setMessages:P,reload:_,append:Y,input:W,setInput:V,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:H,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:K}}const si=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ht(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[o,i]=M.useState(s.isDevEnv),[c,l]=M.useState(!1),[d,u]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),f=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),v=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:T}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:k,append:w,input:L,setInput:D,isLoading:O,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:E,llmUsage:F,errorMessage:P}=ei();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),M.useEffect(()=>{var H;v&&((H=a.current)==null||H.focus(),m({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[v,f,m]);function _(H,Q){Q==="sql"?(g(H),x(!0)):Q==="python"&&(C(H),x(!0))}function z(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],u(!0)}function Y(){h.selectedEntities.length===0&&m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function W(H){Y();const Q={role:"user",content:H.title+" "+H.subtitle};w(Q)}function V(H){Y(),w({role:"user",content:H})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:l,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:z,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:E,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!T&&e.jsx(s.Placeholders,{onClick:W,placeholders:si}),e.jsx("div",{children:U&&T&&e.jsx(s.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:D,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Y(),I(H)},isLoading:O,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:d,onOpenChange:u,dataSource:f||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function bn(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Nn(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function ti(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function Ss(t,a){const n=bn(a,t),r=s.getDataType(t.dataType),o=r==="date",i={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",l=Nn(t.label,c);return{...i,role:"metric",label:l,aggregate:c}}return a==="groupBy"?{...i,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...i,role:"pivotby"}:a==="sortBy"?{...i,role:"sortby",label:t.label,direction:"asc"}:null}function Cn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const i=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return i===t&&c===a||i===a&&c===t})}function ni(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Cn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ws(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Ds(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Ws=t=>{var D;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:l,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),h=s.useEditorStore(O=>O.card.type),m=t==null?void 0:t.id,p=M.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),f=M.useCallback((O,A)=>{if(m)switch(O){case"groupBy":{a(m,{groupByColumns:A});break}case"metrics":{a(m,{metricColumns:A});break}case"pivotBy":{a(m,{pivotByColumns:A});break}case"sortBy":{a(m,{sortByColumns:A});break}}},[m,a]),g=M.useCallback((O,A,I)=>{if(!m)return;const E=p(O)[A];if(E)switch(O){case"groupBy":n(m,E.id,{label:I});break;case"metrics":r(m,E.id,{label:I});break;case"pivotBy":o(m,E.id,{label:I});break;case"sortBy":i(m,E.id,{label:I});break}},[m,p,n,r,o,i]),x=M.useCallback((O,A)=>{if(!m)return;const y=p("metrics")[O];y&&r(m,y.id,{aggregate:A,label:Nn(y.name,A)})},[m,p,r]),v=M.useCallback((O,A,I)=>{if(!m)return;const E=p("groupBy")[O];if(!E)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(m,E.id,F)},[m,p,n]),j=M.useCallback((O,A)=>{if(!m)return;const y=p("groupBy")[O];y&&n(m,y.id,{granularity:A})},[m,p,n]),b=M.useCallback((O,A)=>{if(!m)return;const y=p("metrics")[O];y&&r(m,y.id,{aliasTemplate:A})},[m,p,r]),C=M.useCallback((O,A)=>{if(console.log("handleValueAliasesChange",O,A),!m)return;console.log("handleValueAliasesChange",O,A);const y=p("metrics")[O];y&&(console.log("handleValueAliasesChange",A),r(m,y.id,{valueAliases:A}))},[m,p,r]),R=M.useCallback(O=>{m&&a(m,{comparisonType:O})},[m,a]),T=M.useCallback(O=>{m&&a(m,{showTrendline:O})},[m,a]),S=M.useCallback(O=>{m&&a(m,{trendlineWindow:O})},[m,a]),N=M.useCallback(O=>{m&&a(m,{trendlineGranularity:O})},[m,a]),k=M.useCallback(O=>{m&&a(m,{targetValue:O})},[m,a]),w=M.useCallback(O=>{var _;if(!m)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=ni(O,A,I);if(!y.isValid){y.showError&&ws();return}const E=ti(O),F=p(E);if(Ds(O,F))return;const P=Ss(O,E);P&&f(E,[...F,P])},[m,(D=t==null?void 0:t.config)==null?void 0:D.joinPlan,p,f]),L=M.useCallback((O,A)=>{if(!m)return;const y=p(O)[A];if(y){if(O!=="sortBy"){const E=p("sortBy"),F=E.filter(P=>!(P.name===y.name&&P.qualifiedEntityName===y.qualifiedEntityName));F.length!==E.length&&a(m,{sortByColumns:F})}switch(O){case"groupBy":c(m,y.id);break;case"metrics":l(m,y.id);break;case"pivotBy":d(m,y.id);break;case"sortBy":u(m,y.id);break}}},[m,p,c,l,d,u,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:T,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:k,cardType:h}};function ai({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=s.useSortable({id:t.id}),[l,d]=M.useState(!1),u=s.useEditorStore(x=>x.card),{handleFieldClick:h}=Ws(u),m={transform:s.CSS.Transform.toString(o),transition:i},p=s.getDataType(t.dataType),g=(x=>{const v=(x||"").toLowerCase();switch(s.getDataType(v)){case"number":return As;case"date":return s.Calendar;case"boolean":return Tt;case"json":return Zn;case"geo":return va;default:return Et}})(t.dataType);return e.jsxs("div",{ref:r,style:m,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(g,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),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/90 hover:text-foreground dark:text-muted-foreground ${l?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),l&&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(kt,{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(Ma,{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 ri(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:l,error:d}=s.useColumns(),u=i.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},p=(n==="all"?u:u.filter(C=>h(C)===n)).reduce((C,R)=>{const T=R.qualifiedEntityName||"Other Fields";return C[T]||(C[T]={label:s.toLabel(R.entityName),fields:[]}),C[T].fields.push(R),C},{}),g=Object.keys(p),x=u.filter(C=>h(C)==="dimensions").length,v=u.filter(C=>h(C)==="metrics").length,j=u.filter(C=>h(C)==="calculated").length,b=u.length>0;return l?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[i.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Jn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(p).map(([C,R])=>{const T=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 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:T.label||T.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(ai,{field:S},S.id))})})]},C)})}),Object.keys(p).length===0&&i.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&i.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 oi(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ri,{})," "]})}function ii({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[o,i]=M.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,N={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,N]}),i(new Set([...o,N.id]))},l=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),i(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var D,O;const k=n.joins.find(A=>A.id===S);if(!k)return;const w={...k,...N},L=n.joins.map(A=>A.id===S?w:A);if((D=w.source)!=null&&D.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var P;return F.name===((P=w.source)==null?void 0:P.name)}),I=a.find(F=>{var P;return F.name===((P=w.target)==null?void 0:P.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},E=[...w.joinKeyGroups];E[0]={...E[0],keys:[y]},w.joinKeyGroups=E,L[L.findIndex(F=>F.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:l,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N>0){const k=[...n.joins],w={...k[N]},L={...k[N-1]};k[N]=L,k[N-1]=w,k.forEach((O,A)=>{O.sequence=A+1});const D={...n,joins:k};r(D)}},moveJoinDown:S=>{const N=n.joins.findIndex(k=>k.id===S);if(N<n.joins.length-1){const k=[...n.joins],w={...k[N]},L={...k[N+1]};k[N]=L,k[N+1]=w,k.forEach((O,A)=>{O.sequence=A+1});const D={...n,joins:k};r(D)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),i(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const k=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:k},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const k=n.joins.find(L=>L.id===S);if(!k)return;const w=[...k.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const k=n.joins.find(A=>A.id===S);if(!k)return;const w=a.find(A=>A.name===k.source.name),L=a.find(A=>A.name===k.target.name),D=[...k.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};D[N]={...D[N],keys:[...D[N].keys,O]},d(S,{joinKeyGroups:D})},updateJoinKey:(S,N,k,w,L)=>{const D=n.joins.find(E=>E.id===S);if(!D)return;const O=a.find(E=>E.name===D.source.name),A=a.find(E=>E.name===D.target.name),I=[...D.joinKeyGroups],y=I[N].keys[k];w==="sourceColumnName"&&O?I[N].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[N].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[k]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,k)=>{const w=n.joins.find(D=>D.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(k,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
|
|
420
420
|
FROM ${N.name}`;return S.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const D=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var E,F,P,_;return((E=y.source)==null?void 0:E.name)&&((F=y.target)==null?void 0:F.name)&&((P=y.source)==null?void 0:P.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),O=D.length>1?D.join(" OR "):D[0]||"condition_here";k+=`
|
|
421
421
|
${w.joinType} JOIN ${L.name}
|
|
422
|
-
ON ${O}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function li({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:l,expandedJoins:d,setJoinPlan:u,addJoin:h,removeJoin:m,updateJoin:p,moveJoinUp:f,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:T,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:k,isValidConfiguration:w}=ii({initialJoinPlan:t,availableDataSources:a}),L=D=>{const O=c.find(A=>A.entityName===D);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:l.baseEntity.name,onValueChange:D=>{const O=a.find(A=>A.name===D);u({...l,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:D,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(D=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.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:l.joins.map(D=>{const O=a.find(y=>y.name===D.source.name),A=a.find(y=>y.name===D.target.name),I=d.has(D.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:D.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",D.sequence,O&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(D.id),disabled:D.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(D.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(D.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:D.source.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(D.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(D.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:y=>p(D.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:D.target.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(D.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},disabled:!D.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:D.source.name?j(D.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),D.source.name&&D.target.name&&O&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((y,E)=>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 ",E+1]}),E>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>C(D.id,E,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(D.id,E),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,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:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>S(D.id,E,P,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(D.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>S(D.id,E,P,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>S(D.id,E,P,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(D.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,E,P),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(D.id,E),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(l),disabled:!w(),children:"Save"})]})]})}function pt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:l}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(li,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:l,onRemove:i})]}),t]})}function ci({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,l)=>c.sequence-l.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const l=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(d=>d.name===o.source.name),l=n.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",l==null?void 0:l.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function di(){var h,m;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=M.useState(!1),i=((m=t==null?void 0:t.dataSource)==null?void 0:m.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),o(!1)},l=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const p=[...n.joins].sort((x,v)=>x.sequence-v.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
422
|
+
ON ${O}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function li({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:l,expandedJoins:d,setJoinPlan:u,addJoin:h,removeJoin:m,updateJoin:p,moveJoinUp:f,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:T,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:k,isValidConfiguration:w}=ii({initialJoinPlan:t,availableDataSources:a}),L=D=>{const O=c.find(A=>A.entityName===D);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:l.baseEntity.name,onValueChange:D=>{const O=a.find(A=>A.name===D);u({...l,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:D,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(D=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),l.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:l.joins.map(D=>{const O=a.find(y=>y.name===D.source.name),A=a.find(y=>y.name===D.target.name),I=d.has(D.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:D.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",D.sequence,O&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(D.id),disabled:D.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(D.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(D.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:D.source.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(D.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(D.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:y=>p(D.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:D.target.name,onValueChange:y=>{const E=a.find(F=>F.name===y);p(D.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},disabled:!D.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:D.source.name?j(D.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),D.source.name&&D.target.name&&O&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((y,E)=>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 ",E+1]}),E>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>C(D.id,E,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(D.id,E),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,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:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>S(D.id,E,P,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(D.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>S(D.id,E,P,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>S(D.id,E,P,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(D.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,E,P),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(D.id,E),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(l),disabled:!w(),children:"Save"})]})]})}function xt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:l}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(li,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:l,onRemove:i})]}),t]})}function ci({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,l)=>c.sequence-l.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const l=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(d=>d.name===o.source.name),l=n.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",l==null?void 0:l.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function di(){var h,m;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=M.useState(!1),i=((m=t==null?void 0:t.dataSource)==null?void 0:m.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),o(!1)},l=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const p=[...n.joins].sort((x,v)=>x.sequence-v.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
423
423
|
FROM ${f.name}`;return p.forEach(x=>{const v=i.find(C=>C.name===x.target.name);if(!v)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(T=>{var S,N,k,w;return((S=T.source)==null?void 0:S.name)&&((N=T.target)==null?void 0:N.name)&&((k=T.source)==null?void 0:k.entityName)&&((w=T.target)==null?void 0:w.entityName)}).map(T=>`${T.source.entityName}.${T.source.name} ${T.operator} ${T.target.entityName}.${T.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
|
|
424
424
|
${x.joinType} JOIN ${v.name}
|
|
425
|
-
ON ${b}`}),g};return i.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(ci,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:u})})]})}),e.jsx(pt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(pt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function ui({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),i=o.find(l=>l.label==="Description"),c=o.filter(l=>l.label==="Description"?!1:!["Connection","Database","Schema"].includes(l.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((l,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},d))})]})})}function mi({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),i=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),i.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:i.map((c,l)=>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})]},l))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function hi({isVisible:t,onToggleVisibility:a}){const[n,r]=M.useState(!1),[o,i]=M.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:l}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!o}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>i(!o),children:[o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((h,m)=>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(h),e.jsx("button",{onClick:p=>{p.stopPropagation();const f=u.selectedEntities.filter(g=>!(g.name===h.name&&g.type===h.type));l({...d,...c,selectedEntities:f})},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(ui,{entity:h})]},`${h.type}-${h.name}-${m}`)),u.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})}),e.jsx(mi,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(di,{})]})]}),e.jsx(oi,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Je=[{id:"table",icon:rs,label:"Table"},{id:"bar",icon:ts,label:"Bar Chart"},{id:"line",icon:ns,label:"Line Chart"},{id:"area",icon:bt,label:"Area Chart"},{id:"stackedBar",icon:ks,label:"Stacked Bar Chart"},{id:"combo",icon:Yn,label:"Combo Chart"},{id:"stackedLine",icon:Gs,label:"Stacked Line Chart"},{id:"scatter",icon:Es,label:"Scatter Chart"},{id:"bubble",icon:$s,label:"Bubble Chart"},{id:"pie",icon:as,label:"Pie Chart"},{id:"doughnut",icon:Is,label:"Doughnut Chart"},{id:"funnel",icon:qs,label:"Funnel Chart"},{id:"radar",icon:Ls,label:"Radar Chart"},{id:"polarArea",icon:Us,label:"Polar Area Chart"},{id:"tornado",icon:Rs,label:"Tornado Chart"},{id:"range",icon:Ts,label:"Range Chart"},{id:"kpi",icon:Hs,label:"KPI"},{id:"text",icon:vt,label:"Text"},{id:"map",icon:Ms,label:"Map"}],Js=t=>{const a=t.toLowerCase();for(const n of Je)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},xi="chart-selector-standard-first";function pi(){const[t,a]=s.useLocalStorageState(xi,!0);return{standardFirst:t,updatePreference:a}}const ft=({pluginVisual:t,index:a,onSelect:n})=>{const r=ls(t.icon||""),o=t.name.charAt(0).toUpperCase(),i=Js(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):i||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},gt=["default","standardPlugin","customPlugin"];function fi({selectedChart:t,onChartChange:a}){var S;const[n,r]=M.useState([]),[o,i]=M.useState(!1),{data:c}=Vs();pi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";Bs(d);const{setCardType:u,setCardPreferences:h,setIsDevMode:m}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:p,setCustomCardPreferences:f,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>x?[x,...gt.filter(N=>N!==x)]:gt,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(D){return console.error(`Failed to load manifest for plugin ${L.label}`,D),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){p(null),h({}),u(N),["custom","text","map"].includes(N)&&(m(!0),g(void 0)),a(N),i(!1)}function C(N){p(null),h({}),u("custom"),f({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),i(!1)}const R=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const N=Je.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},T=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,D=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(D&&O)return e.jsx(gi,{icon:D,componentName:O});if(O){const A=Js(O);if(A)return A}return e.jsx(Ue,{className:"h-4 w-4"})}const N=Je.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(Ue,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:k=>v(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Je.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>b(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(N==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(ft,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(ft,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const gi=({icon:t,componentName:a})=>{const n=ls(),r=Js(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ue,{className:"h-4 w-4"})},wn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function ji({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[o,i]=M.useState(!1),c=(d=s.useEditorStore(u=>{var h;return(h=u.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],l=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:l,value:o?n:t,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),i(!1)):u.key==="Escape"&&(r(t),i(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function yi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[o,i]=M.useState(""),[c,l]=M.useState(""),d=()=>{a({...t,"":""})},u=m=>{const p={...t};delete p[m],a(p)},h=m=>{const p={...t};delete p[m],p[o]=c,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([m,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(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 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:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),l(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),l(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+f)),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 jt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=M.useState(t??""),[l,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(i),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:l?i:t??"",onChange:m=>{c(m.target.value),d(!0)},onFocus:()=>d(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&l&&i!==t?u():m.key==="Escape"&&h()},"aria-label":n||"Edit field"}),l&&i!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function vi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var Zs;const{attributes:l,listeners:d,setNodeRef:u,transform:h,transition:m,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(X=>X.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=Ws(f),[L,D]=M.useState(!1),[O,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[E,F]=M.useState(!!t.customFormat),[P,_]=M.useState(t.granularity||"day"),[z,Y]=M.useState(t.aliasTemplate||""),[W,V]=M.useState(t.valueAliases||{}),$=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&v(n,X,""))},q=X=>{y(X),a==="groupBy"&&v(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&j(n,X)},H=X=>{Y(X),a==="metrics"&&b(n,X)},Q=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{g(a,n,X)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(h),transition:m},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",K=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],B=!oe&&a!=="pivotBy",J=oe&&se&&a==="groupBy",ie=!oe&&se&&a==="groupBy",ye=oe&&se&&a==="groupBy",De=oe&&a==="metrics"&&((Zs=f.config)==null?void 0:Zs.comparisonType)==="target",ne=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce=()=>B?e.jsx(jt,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,Xs=()=>J?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:P,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,Tn=()=>ie?e.jsxs(e.Fragment,{children:[Xs(),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:E?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:K.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),E&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:X=>{X.stopPropagation(),q(X.target.value)},onClick:X=>X.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,En=()=>{var X,ve,Re,et,st;return ye?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=f.config)==null?void 0:X.comparisonType)||"none",onValueChange:T,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ve=f.config)==null?void 0:ve.showTrendline)||!1,onCheckedChange:S})]})}),((Re=f.config)==null?void 0:Re.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((et=f.config)==null?void 0:et.trendlineWindow)||30,onChange:Mn=>{const Ln=parseInt(Mn.target.value)||30;N(Ln)},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:((st=f.config)==null?void 0:st.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},In=()=>{var X,ve;return De?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(jt,{value:((X=f.config)==null?void 0:X.targetValue)!==void 0&&((ve=f.config)==null?void 0:ve.targetValue)!==null?String(f.config.targetValue):"",onSave:Re=>{!isNaN(Number(Re))&&Re!==null?w(Number(Re)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},An=()=>ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{x(n,X)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(vn,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ji,{aliasTemplate:z,onAliasTemplateChange:H}),e.jsx(yi,{valueAliases:W,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...l,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(wn,{dataType:ae}),e.jsx(Ks,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),D(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ve=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ve),o(ve)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),ce(),Xs(),Tn(),En(),In(),An()]})]})}function bi({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Qe({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),h=s.useEditorStore(g=>g.card.type),m=a.length>0,p=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(bi,{concept:t})]}),e.jsx("div",{ref:l,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(vi,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>p(g.id,b),hasPivotColumns:i,cardType:h})})},g.id)})})})})]})}function Ni({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(m=>m.card),i=o==null?void 0:o.type,c=t.length>0||n.length>0,l=i!=="kpi",d=i!=="kpi"&&c,u=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),l&&e.jsx(Qe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Qe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Qe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Ci({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=s.useEditorStore(m=>m.showAIDialog),l=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(m=>m.card),{data:h}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col bg-muted/20",children:[e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(fi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:l||h}),children:e.jsx(is,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ia,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(Ni,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Si({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:o,isLoading:i}=s.useColumns(),l=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=T=>{const S=N=>{if(N.id===T){const k=l[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=T=>{const S=N=>{if(N.id===T){const k=l[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=(T,S)=>{const N=k=>k.id===T?{...k,conditions:k.conditions.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},p=(T,S)=>{const N=k=>k.id===T?{...k,groups:k.groups.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},f=(T,S,N,k)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===T?{...L,conditions:L.conditions.map(D=>D.id===S?{...D,[N]:k}:D)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(T,S,N)=>{const k=w=>w.id===T?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(T,S)=>{const N=k=>k.id===T?{...k,logicalOperator:S}:{...k,groups:k.groups.map(N)};r(N(n))},v=(T,S)=>{const N=k=>k.id===T?{...k,negate:S}:{...k,groups:k.groups.map(N)};r(N(n))},j=(T,S,N)=>{const k=w=>w.id===T?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},b=(T,S,N)=>{const k=w=>w.id===T?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},C=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const S=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let D=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(k.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(k.operator)){let O=[];Array.isArray(D)?O=D.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof D=="string"?O=D.split(",").map(A=>{const I=A.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(O=[String(D)]),D=`(${O.join(", ")})`}switch(L){case"contains":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${w} LIKE '${D.replace(/'/g,"")}%'`:`${w} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;default:return`${w} ${L} ${D}`}},N=k=>{const w=k.conditions.map(S),L=k.groups.map(I=>N(I)),D=[...w,...L].filter(Boolean);if(D.length===0)return"";const O=D.join(` ${k.logicalOperator} `),A=D.length>1?`(${O})`:O;return k.negate?`NOT ${A}`:A};return N(T)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:u,addGroup:h,removeCondition:m,removeGroup:p,updateCondition:f,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function wi({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Di=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(ia,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},ki=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ti({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=M.useState(!1),l=M.useMemo(()=>{const d={};return n.forEach(u=>{const h=ki(u);d[h]||(d[h]={}),d[h][u.entityId]||(d[h][u.entityId]=[]),d[h][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(wi,{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(l).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([h,m])=>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:[Di(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((p,f)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+f))]},`${d}-${h}`))},d))})]})})]})}function Ys(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...i,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[l]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:h,isPending:m,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:m,error:p}}function Ei({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=ue.useState(!1),{filterValues:l}=Ys(t),d=h=>{n(a.filter(m=>m!==h))},u=h=>{a.includes(h)?n(a.filter(m=>m!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const m=l.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):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:l.map((h,m)=>e.jsxs(s.CommandItem,{onSelect:()=>u(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+m))})]})]})})]})})}const Dn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Dn(n)}),a};function Ii({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:l}=Ys(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..."]}):l?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:i.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ai=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Mi=["=","!=","contains","startsWith","endsWith","in","not in"],Li=["=","!=",">",">=","<","<=","in","not in"],Ri=["=","!="],Oi=["=","!=",">",">=","<","<=","in","not in"];function Bi(t){switch(t){case"string":return Mi;case"number":return Li;case"boolean":return Ri;case"date":return Oi;default:return Ai}}function kn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:l,updateConditionFields:d}){const{attributes:u,listeners:h,setNodeRef:m,transform:p,transition:f,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=Ys(t.field),j={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:m,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Ti,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:l,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Bi(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Ei,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ii,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Fi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:h,onAddCondition:m,onAddGroup:p,availableFields:f,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:T}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id){const O=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===D.id);O!==-1&&A!==-1&&u(t.id,O,A)}},k=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===D.id);O!==-1&&A!==-1&&h(n,O,A)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${T?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(kn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Pi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:l,addCondition:d,addGroup:u,removeCondition:h,removeGroup:m,updateCondition:p,updateConditionFields:f,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=Si({initialFilters:t,availableFields:a}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=M.useState(!1),k=(D,O,A)=>{const I=y=>y.id===D?{...y,conditions:y.conditions.map(E=>E.id===O?{...E,field:A,dataType:A.dataType}:E)}:{...y,groups:y.groups.map(I)};R(I(i))},w=(D,O=0,A)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=D.conditions.findIndex(_=>_.id===y.id),P=D.conditions.findIndex(_=>_.id===E.id);F!==-1&&P!==-1&&v(D.id,F,P)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,y)=>e.jsx(kn,{condition:I,index:y,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:f},I.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=D.groups.findIndex(_=>_.id===y.id),P=D.groups.findIndex(_=>_.id===E.id);F!==-1&&P!==-1&&j(D.id,F,P)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,O+1,D.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(Fi,{group:D,depth:O,parentGroupId:A,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:m,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:f},D.id),L=Dn(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:[l?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>N(!!D)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?i:null),children:"Apply Filters"})]})]})}function zi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const l=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Pi,{filters:a,availableFields:o,onSave:l,onCancel:()=>c(!1),onClearAll:d})]})]})}function _i({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var f;const[o,i]=M.useState(null),c=s.useEditorStore(g=>g.card),l=(f=c==null?void 0:c.config)==null?void 0:f.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=M.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),h=M.useCallback(g=>{i(g.active.id)},[]),m=M.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){i(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){i(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const T=[...a].find(w=>w.id===j);if(!T){i(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){i(null);return}if(w!==T.qualifiedEntityName&&T.qualifiedEntityName)if(l){if(!Sn(w,T.qualifiedEntityName,l)){ws(),i(null);return}}else{ws(),i(null);return}}const N=n(R);if(Ds(T,N)){i(null);return}const k=Ss(T,R);i(null),r(R,[...N,k]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const T=n(C),S=n(R),N=T.find(L=>L.id===j);if(!N){i(null);return}const k=Ss(N,R);if(i(null),R==="sortBy"){if(C==="pivotBy"){i(null);return}Ds(N,S)||r(R,[...S,k]);return}const w=T.filter(L=>L.id!==j);r(C,w),r(R,[...S,k]);return}if(C&&R&&C===R&&C!=="source"){const T=n(C),S=T.findIndex(k=>k.id===j),N=T.findIndex(k=>k.id===b);if(S!==N){const k=s.arrayMove(T,S,N);r(C,k)}}i(null)},[t,a,n,r,u,l]),p=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:p,handleDragStart:h,handleDragEnd:m}}function Vi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(f=>f.isDevMode),o=s.useEditorStore(f=>f.card);s.isExplorerCard(o);const{config:i}=M.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showAdvancedMode)!==!1,{setIsDevMode:l}=s.useEditorActions(),d=s.useEditorStore(f=>f.showAIDialog),u=s.useEditorStore(f=>f.frame),h=s.useManagementStore(f=>f.selectedVisual),m=(h==null?void 0:h.id)===(u==null?void 0:u.id),{setShowAIDialog:p}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between bg-muted/20 px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>l(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_s,{}),n&&!m&&e.jsx(zs,{variant:"default"}),m&&e.jsx(Jr,{}),a&&s.isDevEnv]})]})}function Ui({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const $i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function qi(){var d,u;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[o,i]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},l=h=>{const m=h.target.value;i(m),m&&!isNaN(parseInt(m))&&a(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:$i.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Gi({isOpen:t,onClose:a}){const n=Ut(a,{enabled:t}),r=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.url)||""}),o=s.useEditorStore(h=>h.card),i=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.pluginChartType)||""}),c=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.settings)||{}}),{data:l}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(l==null?void 0:l.records)||[],chartType:i,settings:c})})})]})})}function Hi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d,activeCard:u,columns:h,columnsLoading:m,columnsError:p}){var O;const f=s.useEditorStore(A=>A.card),g=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(A=>A.showAIDialog),[j,b]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:R,errorMessage:T,isPending:S,isLoading:N,isFetching:k}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!f.config)return;if(!A.length){x(f.id,{...f.config,sortByColumns:[]});return}const I=f.config,y=A.map(({id:E,desc:F})=>{var Y,W;const P=(Y=I.metricColumns)==null?void 0:Y.find(V=>V.label===E),_=(W=I.groupByColumns)==null?void 0:W.find(V=>V.label===E),z=P||_;return z?{id:Nn("sortBy",z),name:z.name,dataType:z.dataType,label:z.label,qualifiedEntityName:z.qualifiedEntityName,entityId:z.entityId,entityName:z.entityName,entityType:z.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(E=>E!==null);x(f.id,{...I,sortByColumns:y})},D=M.useMemo(()=>{var A,I;return(I=(A=f.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=f.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Vi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(mn,{variant:"outline"}),e.jsx(Ui,{activeView:t,onViewChange:a}),l&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:l,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(qi,{})}),v&&e.jsx(is,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(hn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(ka,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(xn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:D})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(an,{sql:R==null?void 0:R.sql,error:T})]})})]}),e.jsx(Gi,{isOpen:j,onClose:()=>b(!1)})]})]})}function Ki({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(wn,{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 Qi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Wi(){var V,$;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[o,i]=M.useState(!1),[c,l]=M.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:h}=s.useEditorActions(),m=s.useEditorStore(q=>q.card.type);M.useEffect(()=>Qi(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},f=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{i(!0)},v=q=>{h(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:T,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:A,setFieldsForContainer:I}=Ws(O),{activeField:y,handleDragStart:E,handleDragEnd:F}=_i({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:I}),P=(q,U)=>{U&&N(q,U)},_=q=>{var U;T(q,{config:{...(U=j.cards.find(H=>H.id===q))==null?void 0:U.config,filters:void 0}})},z=k,Y=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(H=>{U+=Y(H)}),U},W=Y(((V=O==null?void 0:O.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(hi,{isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Ci,{selectedChart:m,onChartChange:v,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx(Hi,{selectedChart:m,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:g,onFiltersClick:x,filterCount:W,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed bottom-4 left-4 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:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(zi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:P,onClearFilters:_,availableFields:z,isOpen:o,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ki,{activeField:y||null})})]})}function Ji({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),i=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:l,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:m,handleDragStart:p,handleDragCancel:f,sensors:g}=Fr();M.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),l(!0)):(l(!1),(C=r.current)==null||C.resize(0))},[o,l]);function x(b){b<1?l(!1):o||l(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(tn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Zo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(xt,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Wi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(xt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx(s.DndContext,{sensors:g,onDragStart:p,onDragEnd:m,onDragOver:h,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Yi(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ji,{onSave:o,onClose:i})})}function Xi(){const t=s.useEditorStore(i=>i.selectedDatabaseName),a=s.useEditorStore(i=>i.selectedTableName),n=s.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(l=>l.column===s.fmt(i.column_name)&&l.table===a&&l.database===t);return e.jsx("div",{onClick:()=>o(i),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(Fs,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Zi(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(tn,{type:"filter",ColumnsComponent:()=>e.jsx(Xi,{})})})]})}function el(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function sl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(el,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Zi,{})})]})}function tl(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function nl({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(tl,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Mr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yi,{}),e.jsx(sl,{})]})]})]})]})})}exports.DashboardPlus=nl;exports.ResourceManagementPanel=en;exports.ScheduleDashboard=Rt;exports.SelectComponent=Pe;exports.cleanCard=At;exports.downloadPdf=Lt;exports.getDashbaordStateWithoutData=Os;
|
|
425
|
+
ON ${b}`}),g};return i.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(ci,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:u})})]})}),e.jsx(xt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(xt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function ui({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),i=o.find(l=>l.label==="Description"),c=o.filter(l=>l.label==="Description"?!1:!["Connection","Database","Schema"].includes(l.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((l,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},d))})]})})}function mi({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),i=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),i.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:i.map((c,l)=>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})]},l))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function hi({isVisible:t,onToggleVisibility:a}){const[n,r]=M.useState(!1),[o,i]=M.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:l}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!o}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>i(!o),children:[o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((h,m)=>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(h),e.jsx("button",{onClick:p=>{p.stopPropagation();const f=u.selectedEntities.filter(g=>!(g.name===h.name&&g.type===h.type));l({...d,...c,selectedEntities:f})},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(ui,{entity:h})]},`${h.type}-${h.name}-${m}`)),u.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})}),e.jsx(mi,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(di,{})]})]}),e.jsx(oi,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Je=[{id:"table",icon:rs,label:"Table"},{id:"bar",icon:ts,label:"Bar Chart"},{id:"line",icon:ns,label:"Line Chart"},{id:"area",icon:vt,label:"Area Chart"},{id:"stackedBar",icon:ks,label:"Stacked Bar Chart"},{id:"combo",icon:Yn,label:"Combo Chart"},{id:"stackedLine",icon:Gs,label:"Stacked Line Chart"},{id:"scatter",icon:Es,label:"Scatter Chart"},{id:"bubble",icon:$s,label:"Bubble Chart"},{id:"pie",icon:as,label:"Pie Chart"},{id:"doughnut",icon:Is,label:"Doughnut Chart"},{id:"funnel",icon:qs,label:"Funnel Chart"},{id:"radar",icon:Ls,label:"Radar Chart"},{id:"polarArea",icon:Us,label:"Polar Area Chart"},{id:"tornado",icon:Rs,label:"Tornado Chart"},{id:"range",icon:Ts,label:"Range Chart"},{id:"kpi",icon:Hs,label:"KPI"},{id:"text",icon:yt,label:"Text"},{id:"map",icon:Ms,label:"Map"}],Js=t=>{const a=t.toLowerCase();for(const n of Je)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},xi="chart-selector-standard-first";function pi(){const[t,a]=s.useLocalStorageState(xi,!0);return{standardFirst:t,updatePreference:a}}const pt=({pluginVisual:t,index:a,onSelect:n})=>{const r=ls(t.icon||""),o=t.name.charAt(0).toUpperCase(),i=Js(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):i||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ft=["default","standardPlugin","customPlugin"];function fi({selectedChart:t,onChartChange:a}){var S;const[n,r]=M.useState([]),[o,i]=M.useState(!1),{data:c}=Vs();pi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";Bs(d);const{setCardType:u,setCardPreferences:h,setIsDevMode:m}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:p,setCustomCardPreferences:f,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>x?[x,...ft.filter(N=>N!==x)]:ft,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(D){return console.error(`Failed to load manifest for plugin ${L.label}`,D),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){p(null),h({}),u(N),["custom","text","map"].includes(N)&&(m(!0),g(void 0)),a(N),i(!1)}function C(N){p(null),h({}),u("custom"),f({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),i(!1)}const R=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const N=Je.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},T=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,D=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(D&&O)return e.jsx(gi,{icon:D,componentName:O});if(O){const A=Js(O);if(A)return A}return e.jsx(Ue,{className:"h-4 w-4"})}const N=Je.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(Ue,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:k=>v(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Je.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>b(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(N==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(pt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(pt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const gi=({icon:t,componentName:a})=>{const n=ls(),r=Js(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ue,{className:"h-4 w-4"})},Sn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function ji({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[o,i]=M.useState(!1),c=(d=s.useEditorStore(u=>{var h;return(h=u.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],l=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:l,value:o?n:t,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),i(!1)):u.key==="Escape"&&(r(t),i(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function yi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[o,i]=M.useState(""),[c,l]=M.useState(""),d=()=>{a({...t,"":""})},u=m=>{const p={...t};delete p[m],a(p)},h=m=>{const p={...t};delete p[m],p[o]=c,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([m,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(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 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:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),l(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),l(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+f)),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 gt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=M.useState(t??""),[l,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(i),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:l?i:t??"",onChange:m=>{c(m.target.value),d(!0)},onFocus:()=>d(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&l&&i!==t?u():m.key==="Escape"&&h()},"aria-label":n||"Edit field"}),l&&i!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function vi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var Xs;const{attributes:l,listeners:d,setNodeRef:u,transform:h,transition:m,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(X=>X.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=Ws(f),[L,D]=M.useState(!1),[O,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[E,F]=M.useState(!!t.customFormat),[P,_]=M.useState(t.granularity||"day"),[z,Y]=M.useState(t.aliasTemplate||""),[W,V]=M.useState(t.valueAliases||{}),$=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&v(n,X,""))},q=X=>{y(X),a==="groupBy"&&v(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&j(n,X)},H=X=>{Y(X),a==="metrics"&&b(n,X)},Q=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{g(a,n,X)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(h),transition:m},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",K=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],B=!oe&&a!=="pivotBy",J=se&&a==="groupBy",ie=!oe&&se&&a==="groupBy",ye=oe&&se&&a==="groupBy",De=oe&&a==="metrics"&&((Xs=f.config)==null?void 0:Xs.comparisonType)==="target",ne=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce=()=>B?e.jsx(gt,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,kn=()=>J?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:P,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,Tn=()=>ie?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:E?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:K.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),E&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:X=>{X.stopPropagation(),q(X.target.value)},onClick:X=>X.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})}):null,En=()=>{var X,ve,Re,Zs,et;return ye?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=f.config)==null?void 0:X.comparisonType)||"none",onValueChange:T,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ve=f.config)==null?void 0:ve.showTrendline)||!1,onCheckedChange:S})]})}),((Re=f.config)==null?void 0:Re.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((Zs=f.config)==null?void 0:Zs.trendlineWindow)||30,onChange:Mn=>{const Ln=parseInt(Mn.target.value)||30;N(Ln)},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:((et=f.config)==null?void 0:et.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},In=()=>{var X,ve;return De?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(gt,{value:((X=f.config)==null?void 0:X.targetValue)!==void 0&&((ve=f.config)==null?void 0:ve.targetValue)!==null?String(f.config.targetValue):"",onSave:Re=>{!isNaN(Number(Re))&&Re!==null?w(Number(Re)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},An=()=>ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{x(n,X)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(yn,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ji,{aliasTemplate:z,onAliasTemplateChange:H}),e.jsx(yi,{valueAliases:W,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...l,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Sn,{dataType:ae}),e.jsx(Ks,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),D(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ve=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ve),o(ve)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),ce(),kn(),Tn(),En(),In(),An()]})]})}function bi({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Qe({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),h=s.useEditorStore(g=>g.card.type),m=a.length>0,p=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(bi,{concept:t})]}),e.jsx("div",{ref:l,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(vi,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>p(g.id,b),hasPivotColumns:i,cardType:h})})},g.id)})})})})]})}function Ni({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(m=>m.card),i=o==null?void 0:o.type,c=t.length>0||n.length>0,l=i!=="kpi",d=i!=="kpi"&&c,u=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),l&&e.jsx(Qe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Qe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Qe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Ci({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=s.useEditorStore(m=>m.showAIDialog),l=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(m=>m.card),{data:h}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col bg-muted/20",children:[e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(fi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:l||h}),children:e.jsx(is,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ia,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(Ni,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Si({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:o,isLoading:i}=s.useColumns(),l=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=T=>{const S=N=>{if(N.id===T){const k=l[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=T=>{const S=N=>{if(N.id===T){const k=l[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=(T,S)=>{const N=k=>k.id===T?{...k,conditions:k.conditions.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},p=(T,S)=>{const N=k=>k.id===T?{...k,groups:k.groups.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},f=(T,S,N,k)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===T?{...L,conditions:L.conditions.map(D=>D.id===S?{...D,[N]:k}:D)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(T,S,N)=>{const k=w=>w.id===T?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(T,S)=>{const N=k=>k.id===T?{...k,logicalOperator:S}:{...k,groups:k.groups.map(N)};r(N(n))},v=(T,S)=>{const N=k=>k.id===T?{...k,negate:S}:{...k,groups:k.groups.map(N)};r(N(n))},j=(T,S,N)=>{const k=w=>w.id===T?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},b=(T,S,N)=>{const k=w=>w.id===T?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},C=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const S=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let D=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(k.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(k.operator)){let O=[];Array.isArray(D)?O=D.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof D=="string"?O=D.split(",").map(A=>{const I=A.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(O=[String(D)]),D=`(${O.join(", ")})`}switch(L){case"contains":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${w} LIKE '${D.replace(/'/g,"")}%'`:`${w} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;default:return`${w} ${L} ${D}`}},N=k=>{const w=k.conditions.map(S),L=k.groups.map(I=>N(I)),D=[...w,...L].filter(Boolean);if(D.length===0)return"";const O=D.join(` ${k.logicalOperator} `),A=D.length>1?`(${O})`:O;return k.negate?`NOT ${A}`:A};return N(T)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:u,addGroup:h,removeCondition:m,removeGroup:p,updateCondition:f,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function wi({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Di=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(ia,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},ki=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ti({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=M.useState(!1),l=M.useMemo(()=>{const d={};return n.forEach(u=>{const h=ki(u);d[h]||(d[h]={}),d[h][u.entityId]||(d[h][u.entityId]=[]),d[h][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(wi,{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(l).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([h,m])=>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:[Di(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((p,f)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+f))]},`${d}-${h}`))},d))})]})})]})}function Ys(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...i,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[l]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:h,isPending:m,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:m,error:p}}function Ei({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=ue.useState(!1),{filterValues:l}=Ys(t),d=h=>{n(a.filter(m=>m!==h))},u=h=>{a.includes(h)?n(a.filter(m=>m!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const m=l.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):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:l.map((h,m)=>e.jsxs(s.CommandItem,{onSelect:()=>u(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+m))})]})]})})]})})}const wn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=wn(n)}),a};function Ii({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:l}=Ys(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..."]}):l?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:i.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ai=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Mi=["=","!=","contains","startsWith","endsWith","in","not in"],Li=["=","!=",">",">=","<","<=","in","not in"],Ri=["=","!="],Oi=["=","!=",">",">=","<","<=","in","not in"];function Bi(t){switch(t){case"string":return Mi;case"number":return Li;case"boolean":return Ri;case"date":return Oi;default:return Ai}}function Dn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:l,updateConditionFields:d}){const{attributes:u,listeners:h,setNodeRef:m,transform:p,transition:f,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=Ys(t.field),j={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:m,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Ti,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:l,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Bi(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Ei,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ii,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Fi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:h,onAddCondition:m,onAddGroup:p,availableFields:f,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:T}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id){const O=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===D.id);O!==-1&&A!==-1&&u(t.id,O,A)}},k=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===D.id);O!==-1&&A!==-1&&h(n,O,A)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${T?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Dn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Pi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:l,addCondition:d,addGroup:u,removeCondition:h,removeGroup:m,updateCondition:p,updateConditionFields:f,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=Si({initialFilters:t,availableFields:a}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=M.useState(!1),k=(D,O,A)=>{const I=y=>y.id===D?{...y,conditions:y.conditions.map(E=>E.id===O?{...E,field:A,dataType:A.dataType}:E)}:{...y,groups:y.groups.map(I)};R(I(i))},w=(D,O=0,A)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=D.conditions.findIndex(_=>_.id===y.id),P=D.conditions.findIndex(_=>_.id===E.id);F!==-1&&P!==-1&&v(D.id,F,P)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,y)=>e.jsx(Dn,{condition:I,index:y,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:f},I.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=D.groups.findIndex(_=>_.id===y.id),P=D.groups.findIndex(_=>_.id===E.id);F!==-1&&P!==-1&&j(D.id,F,P)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,O+1,D.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(Fi,{group:D,depth:O,parentGroupId:A,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:m,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:f},D.id),L=wn(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:[l?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>N(!!D)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?i:null),children:"Apply Filters"})]})]})}function zi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const l=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Pi,{filters:a,availableFields:o,onSave:l,onCancel:()=>c(!1),onClearAll:d})]})]})}function _i({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var f;const[o,i]=M.useState(null),c=s.useEditorStore(g=>g.card),l=(f=c==null?void 0:c.config)==null?void 0:f.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=M.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),h=M.useCallback(g=>{i(g.active.id)},[]),m=M.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){i(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){i(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const T=[...a].find(w=>w.id===j);if(!T){i(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){i(null);return}if(w!==T.qualifiedEntityName&&T.qualifiedEntityName)if(l){if(!Cn(w,T.qualifiedEntityName,l)){ws(),i(null);return}}else{ws(),i(null);return}}const N=n(R);if(Ds(T,N)){i(null);return}const k=Ss(T,R);i(null),r(R,[...N,k]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const T=n(C),S=n(R),N=T.find(L=>L.id===j);if(!N){i(null);return}const k=Ss(N,R);if(i(null),R==="sortBy"){if(C==="pivotBy"){i(null);return}Ds(N,S)||r(R,[...S,k]);return}const w=T.filter(L=>L.id!==j);r(C,w),r(R,[...S,k]);return}if(C&&R&&C===R&&C!=="source"){const T=n(C),S=T.findIndex(k=>k.id===j),N=T.findIndex(k=>k.id===b);if(S!==N){const k=s.arrayMove(T,S,N);r(C,k)}}i(null)},[t,a,n,r,u,l]),p=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:p,handleDragStart:h,handleDragEnd:m}}function Vi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(f=>f.isDevMode),o=s.useEditorStore(f=>f.card);s.isExplorerCard(o);const{config:i}=M.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showAdvancedMode)!==!1,{setIsDevMode:l}=s.useEditorActions(),d=s.useEditorStore(f=>f.showAIDialog),u=s.useEditorStore(f=>f.frame),h=s.useManagementStore(f=>f.selectedVisual),m=(h==null?void 0:h.id)===(u==null?void 0:u.id),{setShowAIDialog:p}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between bg-muted/20 px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>l(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_s,{}),n&&!m&&e.jsx(zs,{variant:"default"}),m&&e.jsx(Jr,{}),a&&s.isDevEnv]})]})}function Ui({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const $i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function qi(){var d,u;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[o,i]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},l=h=>{const m=h.target.value;i(m),m&&!isNaN(parseInt(m))&&a(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:$i.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Gi({isOpen:t,onClose:a}){const n=Vt(a,{enabled:t}),r=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.url)||""}),o=s.useEditorStore(h=>h.card),i=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.pluginChartType)||""}),c=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.settings)||{}}),{data:l}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(l==null?void 0:l.records)||[],chartType:i,settings:c})})})]})})}function Hi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d,activeCard:u,columns:h,columnsLoading:m,columnsError:p}){var O;const f=s.useEditorStore(A=>A.card),g=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(A=>A.showAIDialog),[j,b]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:R,errorMessage:T,isPending:S,isLoading:N,isFetching:k}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!f.config)return;if(!A.length){x(f.id,{...f.config,sortByColumns:[]});return}const I=f.config,y=A.map(({id:E,desc:F})=>{var Y,W;const P=(Y=I.metricColumns)==null?void 0:Y.find(V=>V.label===E),_=(W=I.groupByColumns)==null?void 0:W.find(V=>V.label===E),z=P||_;return z?{id:bn("sortBy",z),name:z.name,dataType:z.dataType,label:z.label,qualifiedEntityName:z.qualifiedEntityName,entityId:z.entityId,entityName:z.entityName,entityType:z.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(E=>E!==null);x(f.id,{...I,sortByColumns:y})},D=M.useMemo(()=>{var A,I;return(I=(A=f.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=f.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Vi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(un,{variant:"outline"}),e.jsx(Ui,{activeView:t,onViewChange:a}),l&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:l,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(qi,{})}),v&&e.jsx(is,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(mn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(ka,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(hn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:D})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(nn,{sql:R==null?void 0:R.sql,error:T})]})})]}),e.jsx(Gi,{isOpen:j,onClose:()=>b(!1)})]})]})}function Ki({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Sn,{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 Qi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Wi(){var V,$;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[o,i]=M.useState(!1),[c,l]=M.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:h}=s.useEditorActions(),m=s.useEditorStore(q=>q.card.type);M.useEffect(()=>Qi(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},f=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{i(!0)},v=q=>{h(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:T,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:A,setFieldsForContainer:I}=Ws(O),{activeField:y,handleDragStart:E,handleDragEnd:F}=_i({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:I}),P=(q,U)=>{U&&N(q,U)},_=q=>{var U;T(q,{config:{...(U=j.cards.find(H=>H.id===q))==null?void 0:U.config,filters:void 0}})},z=k,Y=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(H=>{U+=Y(H)}),U},W=Y(((V=O==null?void 0:O.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(hi,{isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Ci,{selectedChart:m,onChartChange:v,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx(Hi,{selectedChart:m,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:g,onFiltersClick:x,filterCount:W,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed bottom-4 left-4 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:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(zi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:P,onClearFilters:_,availableFields:z,isOpen:o,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ki,{activeField:y||null})})]})}function Ji({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),i=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:l,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:m,handleDragStart:p,handleDragCancel:f,sensors:g}=Fr();M.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),l(!0)):(l(!1),(C=r.current)==null||C.resize(0))},[o,l]);function x(b){b<1?l(!1):o||l(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(sn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Zo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(ht,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Wi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(ht,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx(s.DndContext,{sensors:g,onDragStart:p,onDragEnd:m,onDragOver:h,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Yi(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ji,{onSave:o,onClose:i})})}function Xi(){const t=s.useEditorStore(i=>i.selectedDatabaseName),a=s.useEditorStore(i=>i.selectedTableName),n=s.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(l=>l.column===s.fmt(i.column_name)&&l.table===a&&l.database===t);return e.jsx("div",{onClick:()=>o(i),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(Fs,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Zi(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(sn,{type:"filter",ColumnsComponent:()=>e.jsx(Xi,{})})})]})}function el(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function sl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(el,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Zi,{})})]})}function tl(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function nl({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(tl,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Mr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yi,{}),e.jsx(sl,{})]})]})]})]})})}exports.DashboardPlus=nl;exports.ResourceManagementPanel=Zt;exports.ScheduleDashboard=Lt;exports.SelectComponent=Pe;exports.cleanCard=It;exports.downloadPdf=Mt;exports.getDashbaordStateWithoutData=Os;
|