react-semaphor 0.0.563 → 0.0.565
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-BDaSxoPS.js → dashboard-plus-CJI9Flj6.js} +3000 -2936
- package/dist/chunks/{dashboard-plus-D6vt7we-.js → dashboard-plus-CxIpiHa-.js} +20 -20
- package/dist/chunks/{index-DD-bkOqG.js → index-CEZuyo_5.js} +15504 -15033
- package/dist/chunks/{index-DkXwAQmY.js → index-DAHFzWxM.js} +146 -146
- 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 rt=t=>{throw TypeError(t)};var ps=(t,a,n)=>a.has(t)||rt("Cannot "+n);var re=(t,a,n)=>(ps(t,a,"read from private field"),n?n.call(t):a.get(t)),Fe=(t,a,n)=>a.has(t)?rt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(ps(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),ze=(t,a,n)=>(ps(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";var rt=t=>{throw TypeError(t)};var ps=(t,a,n)=>a.has(t)||rt("Cannot "+n);var re=(t,a,n)=>(ps(t,a,"read from private field"),n?n.call(t):a.get(t)),Fe=(t,a,n)=>a.has(t)?rt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(ps(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),ze=(t,a,n)=>(ps(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-DAHFzWxM.js"),I=require("react");require("react-dom");function On(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=On(I);var Ce,Se,de,je,ye,es,Ss,St,Rn=(St=class extends s.Subscribable{constructor(a,n){super();Fe(this,ye);Fe(this,Ce);Fe(this,Se);Fe(this,de);Fe(this,je);Be(this,Ce,a),this.setOptions(n),this.bindMethods(),ze(this,ye,es).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,Ce).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,Ce).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){ze(this,ye,es).call(this),ze(this,ye,Ss).call(this,a)}getCurrentResult(){return re(this,Se)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),ze(this,ye,es).call(this),ze(this,ye,Ss).call(this)}mutate(a,n){var r;return Be(this,je,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,Ce).getMutationCache().build(re(this,Ce),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},Ce=new WeakMap,Se=new WeakMap,de=new WeakMap,je=new WeakMap,ye=new WeakSet,es=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Se,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Ss=function(a){s.notifyManager.batch(()=>{var n,r,o,i,c,l,d,m;if(re(this,je)&&this.hasListeners()){const u=re(this,Se).variables,h=re(this,Se).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,je)).onSuccess)==null||r.call(n,a.data,u,h),(i=(o=re(this,je)).onSettled)==null||i.call(o,a.data,null,u,h)):(a==null?void 0:a.type)==="error"&&((l=(c=re(this,je)).onError)==null||l.call(c,a.error,u,h),(m=(d=re(this,je)).onSettled)==null||m.call(d,void 0,a.error,u,h))}this.listeners.forEach(u=>{u(re(this,Se))})})},St);function Le(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Rn(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),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.
|
|
@@ -123,7 +123,7 @@
|
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
125
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
126
|
+
*/const Os=s.createLucideIcon("ChartScatter",[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/**
|
|
127
127
|
* @license lucide-react v0.453.0 - ISC
|
|
128
128
|
*
|
|
129
129
|
* 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 Tt=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,12 +168,12 @@
|
|
|
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 Rs=s.createLucideIcon("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
|
|
172
172
|
* @license lucide-react v0.453.0 - ISC
|
|
173
173
|
*
|
|
174
174
|
* This source code is licensed under the ISC license.
|
|
175
175
|
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const
|
|
176
|
+
*/const Et=s.createLucideIcon("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/**
|
|
177
177
|
* @license lucide-react v0.453.0 - ISC
|
|
178
178
|
*
|
|
179
179
|
* This source code is licensed under the ISC license.
|
|
@@ -223,7 +223,7 @@
|
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the ISC license.
|
|
225
225
|
* See the LICENSE file in the root directory of this source tree.
|
|
226
|
-
*/const
|
|
226
|
+
*/const Ye=s.createLucideIcon("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
|
|
227
227
|
* @license lucide-react v0.453.0 - ISC
|
|
228
228
|
*
|
|
229
229
|
* This source code is licensed under the ISC license.
|
|
@@ -338,12 +338,12 @@
|
|
|
338
338
|
*
|
|
339
339
|
* This source code is licensed under the ISC license.
|
|
340
340
|
* See the LICENSE file in the root directory of this source tree.
|
|
341
|
-
*/const
|
|
341
|
+
*/const Ge=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
342
342
|
* @license lucide-react v0.453.0 - ISC
|
|
343
343
|
*
|
|
344
344
|
* This source code is licensed under the ISC license.
|
|
345
345
|
* See the LICENSE file in the root directory of this source tree.
|
|
346
|
-
*/const
|
|
346
|
+
*/const He=s.createLucideIcon("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
|
|
347
347
|
* @license lucide-react v0.453.0 - ISC
|
|
348
348
|
*
|
|
349
349
|
* This source code is licensed under the ISC license.
|
|
@@ -363,17 +363,17 @@
|
|
|
363
363
|
*
|
|
364
364
|
* This source code is licensed under the ISC license.
|
|
365
365
|
* See the LICENSE file in the root directory of this source tree.
|
|
366
|
-
*/const
|
|
366
|
+
*/const Ta=s.createLucideIcon("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
|
|
367
367
|
* @license lucide-react v0.453.0 - ISC
|
|
368
368
|
*
|
|
369
369
|
* This source code is licensed under the ISC license.
|
|
370
370
|
* See the LICENSE file in the root directory of this source tree.
|
|
371
|
-
*/const
|
|
371
|
+
*/const Ea=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
372
372
|
* @license lucide-react v0.453.0 - ISC
|
|
373
373
|
*
|
|
374
374
|
* This source code is licensed under the ISC license.
|
|
375
375
|
* See the LICENSE file in the root directory of this source tree.
|
|
376
|
-
*/const
|
|
376
|
+
*/const Ve=s.createLucideIcon("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/**
|
|
377
377
|
* @license lucide-react v0.453.0 - ISC
|
|
378
378
|
*
|
|
379
379
|
* 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
|
|
406
|
+
*/const De=s.createLucideIcon("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
|
|
407
407
|
* @license lucide-react v0.453.0 - ISC
|
|
408
408
|
*
|
|
409
409
|
* This source code is licensed under the ISC license.
|
|
@@ -413,7 +413,7 @@
|
|
|
413
413
|
*
|
|
414
414
|
* This source code is licensed under the ISC license.
|
|
415
415
|
* See the LICENSE file in the root directory of this source tree.
|
|
416
|
-
*/const Ma=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ns(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=>Rt(c))}})}})}}function Rt(t){return{...t,customCfg:Aa(t.customCfg),data:[]}}function Aa(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 La(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 Ds(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 Ra(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Oa(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[l,d]=I.useState(!1),[m,u]=I.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function g(){d(!0);const x=ns(h),v=await La(t,x,p,f==null?void 0:f.accessToken);v&&(i([...o||[],v]),c(v.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange: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]=I.useState(!1),n=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:o,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function l(u){i(u)}async function d(u){if(await Ra(u,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==u);o(p||[]),i("original")}}async function m(u){const h=n==null?void 0:n.map(g=>g.id===u.id?{...g,isDefault:!u.isDefault}:{...g,isDefault:!1});o(h||[]);const p={...u,isDefault:!u.isDefault};await Ds(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(g=>g.isDefault);if(f&&f.id!==u.id){const g={...f,isDefault:!1};await Ds(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(ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:l,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Ot(){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 Ft(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Ot();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const l=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(l,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const p=`${o}-${new Date().toISOString()}.pdf`;h.download=p,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function Ba({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 Ft()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className: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 ut=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=za(),[l,d]=I.useState(""),[m,u]=I.useState(ut[0].value),[h,p]=I.useState("06:00"),[f,g]=I.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:ut,value:m,onValueChange:x=>u(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:h,onChange:x=>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:m,time:h,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(Et,{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(mt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Jn,{className:"size-3.5"})}),e.jsx(mt,{tooltip:`${x.endUserEmail}`,children:e.jsx(ja,{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 mt=({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]=I.useState("idle"),[n,r]=I.useState(""),[o,i]=I.useState(null),c=s.useDashboardStore(k=>k.authToken),l=s.useDashboardStore(k=>k.dashboard.id),d=s.useDashboardStore(k=>k.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:l,endUserId:m},{data:p,isLoading:f,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",l,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!l&&!!m});async function j({email:k,subject:O,frequency:E,time:w}){const{authToken:y,...D}=Ot(),b=Intl.DateTimeFormat().resolvedOptions().timeZone,A={email:k,frequency:E,time:w,timezone:b,endUserId:m,endUserEmail:k,subject:O||d||"Scheduled Dashboard",dashboardId:l,dashboardParams:D};a("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(S,(y==null?void 0:y.accessToken)||"",{...A});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function C(k){const O="https://semaphor.cloud/api/v1/subscriptions/delete";i(k);try{await s.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:k}),v(),setTimeout(()=>{i(null)},2e3)}catch(E){console.error(E),i(null),a("error"),r(E.message)}}return{data:p,isLoading:f,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:C,status:t,error:n}}function Le(){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 zt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Pa=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)},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};console.log("data",r);const 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()},Ua=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,{})},$a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Ya=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()},Ga=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)},Ha=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ka(t,a,n,r,o){const{authToken:i}=s.useSemaphorContext(),{currentUser:c}=Le();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Pa((i==null?void 0:i.accessToken)||"",t),enabled:!!(i!=null&&i.accessToken)&&!!c})}function Wa(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 Pt(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>_a((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ua((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 Xa(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 Za(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>$a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function er(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ya((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 sr(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ga((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function tr(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>Ha((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 nr(t,a){return tr(ee.VISUAL,t,a)}function Vt(){const[t,a]=I.useState(new Map),n=I.useCallback((i,c)=>{a(l=>{const d=new Map(l),m=new Set(d.get(i)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(i,m),d})},[]),r=I.useCallback((i,c)=>{a(l=>{const d=new Map(l),m=new Set(d.get(i)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(i):d.set(i,m),d})},[]),o=I.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 _t(t,a,n){var h;const r=Ka(t),o=Wa(t,n),i=Pt(t),c=Ja(t,a),l=Xa(t),d=Za(),m=er(),u={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:i.mutate,deleteResource:c.mutate,duplicateResource:l.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:o.isPending,isUpdating:i.isPending,isDeleting:c.isPending,isDuplicating:l.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function ar(t,a){return _t(ee.DASHBOARD,t,a)}function rr(t,a){return _t(ee.VISUAL,t,a)}function or(){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 ir({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:i,onEditVisual:c,onUpdateVisual:l,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var w;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),g=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[x,v]=I.useState(!1),[j,C]=I.useState(!1);I.useEffect(()=>{n?(v(!0),C(!0)):j&&(v(!1),C(!1))},[n,j]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(It,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{className:"h-3.5 w-3.5 text-slate-500"}),O=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),E=()=>{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:E,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:O()})}),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:y=>l==null?void 0:l(t.id,{title:y}),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:k()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:y=>l==null?void 0:l(t.id,{description:y}),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:y=>{y.stopPropagation(),i(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:v,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:y=>y.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:y=>{y.stopPropagation(),i(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),m(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:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Na,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),g(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),e.jsx("span",{children:((w=t.ownership.createdBy)==null?void 0:w.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 Ut({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 as({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:i=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,l=n.filter(m=>m.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(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function qt({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(as,{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 Yt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),i=l=>{const d=a.find(m=>m.id===l);return(d==null?void 0:d.name)||"Unknown User"},c=l=>{const d=o.find(m=>m.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(ve,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(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 Gt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=I.useRef(null);return I.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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function lr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Ht(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function cr(t,a,n){const r=Ht(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 dr({user:t}){return Ht(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 ur({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:i}){if(!(a!=null&&a.role))return null;const c=lr((r==null?void 0:r.type)||""),l=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),m=d?d.newRole:a==null?void 0:a.role,u=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(as,{currentRole:m,onRoleChange:h=>{i(t.id,a.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:l?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:pe(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function mr({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(Ge,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function hr({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 xr({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||[],m=c.orgWide||[],u=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[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,C;const g=((j=a.find(k=>k.id===p.orgUserId))==null?void 0:j.name)||"Unknown User",x=((C=a.find(k=>k.id===p.orgUserId))==null?void 0:C.type)||"",v=pe(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,C;const g=((j=a.find(k=>k.id===p.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((C=a.find(k=>k.id===p.tenantUserId))==null?void 0:C.type)||"",v=pe(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"]})]})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((p,f)=>{const g=pe(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)})})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,f)=>{const g=pe(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)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,f)=>{const g=pe(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&&!m.length&&!u.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],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,m)=>{var f,g;const u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",p=pe(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),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,m)=>{const u=pe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},m)})})]}),!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 m=((p=a.find(g=>g.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",u=((f=a.find(g=>g.id===l.tenantUserId))==null?void 0:f.type)||"",h=pe(l.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),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 m=pe(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:m})]},d)})})]}),!i.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function pr({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 fr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:i,selectedUser:c,roleOptions:l,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,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?u(t.id):h(t.id):u(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(dr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(as,{currentRole:a==null?void 0:a.role,onRoleChange:g=>p(t.id,a.role,g),roleOptions:l,disabled:!1,allowDropdown:!0}):e.jsx(ur,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>l,handleUpdateAccess:p}),i&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(as,{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(mr,{hasAccess:r,isUserRemoving:n,isSelected:i,hasAccessFromAPI:o}),e.jsx(hr,{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:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const w=u.some(D=>D.id===E),y=h.includes(E);w?g.removeSelectedUser(E):y?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=l||g.updateSelectedUserRole,j=d||g.addUserToRemove,C=m||((E,w,y)=>{g.addUserToUpdate({id:E,currentRole:w,newRole:y})}),k=o,O=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(xr,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:i})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===k.length?g.setSelectedUsers([]):g.setSelectedUsers(k.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===k.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(pr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(E=>{const w=t?cr(E,t,i):void 0,y=O.includes(E.id),D=!!w,b=D&&!y,A=u.some(M=>M.id===E.id),S=u.find(M=>M.id===E.id),R=r(E.type);return e.jsx(fr,{user:E,userShare:w,isUserRemoving:y,hasAccess:b,hasAccessFromAPI:D,isSelected:A,selectedUser:S,roleOptions:R,currentUser:i,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:C,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(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(we,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children: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 Ee=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function gr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:i=!1,isUpdating:c=!1,isRemoving:l=!1}){const d=s.useShareCurrentMode(),m=Ee().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),u=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:u,p=a.role!=="NONE"&&!i&&(!o||o.newRole===u),f=o!==null&&o.newRole!==u,g=i,x=u==="NONE"||!u,v=C=>{switch(C){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(Da,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=C=>{r(u,C)};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(ve,{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:m.map(C=>e.jsxs(s.Button,{variant:h===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(C.value),disabled:n||c||l,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Wt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:i,onRemoveAccess:c,allUsersToUpdate:l,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:m(a.role)}:{role:"NONE"},p=l?{currentRole:m(l.currentRole),newRole:m(l.newRole)}:null,f=(x,v)=>{i(x,v)},g=()=>{c()};return e.jsx(gr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:f,onRemoveAccess:g,allUsersToUpdate:p,allUsersToRemove:d})}const jr=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 yr(t={}){var i,c,l;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=s.useQuery({queryKey:["unified-users",t],queryFn:()=>jr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((i=o.data)==null?void 0:i.users)||[],userContext:(c=o.data)==null?void 0:c.userContext,total:((l=o.data)==null?void 0:l.total)||0,isLoading:o.isLoading,isError:o.isError,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:i}=t,c=I.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&i?{tenantId:i}:{}}),[a,o,i]),{users:l,isLoading:d,isError:m}=yr(c),u=sr(r,n);return{allUsers:l,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function vr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var K,F;const l=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[C,k]=I.useState("specific_users"),O=()=>{if(l==="org")return"organization";if(l==="tenant")return"tenant"},E=()=>{if(l==="tenant"&&d)return d},{allUsers:w,existingShares:y,isLoadingUsers:D}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:O(),tenantId:E()});I.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,C]);const b=_=>{var q,Y;const $=_;if(k($),r==null||r($),j.setCurrentContext("org-tab"),$==="specific_users")j.setCurrentMode("specificOrgUsers");else if($==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(Y=(q=y==null?void 0:y.shares)==null?void 0:q.orgUsersOnly)==null?void 0:Y[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},A=w.filter(_=>_.name.toLowerCase().includes(m.toLowerCase())||_.email.toLowerCase().includes(m.toLowerCase())),S=w.filter(_=>p.some($=>$.id===_.id)),R=_=>{var Q,G;const $=p.some(Z=>Z.id===_),q=f.includes(_),Y=(G=(Q=y==null?void 0:y.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===_);$?j.removeSelectedUser(_):q?j.removeUserFromRemove(_):Y||j.addSelectedUser({id:_,role:"VIEWER"})},M=(_,$)=>{j.updateSelectedUserRole(_,$)},T=_=>{j.addUserToRemove(_),j.removeSelectedUser(_)},N=_=>{j.removeUserFromRemove(_)},L=_=>{j.removeUserFromUpdate(_)},B=(_,$)=>{j.setOrgWideRole($)},P=()=>{j.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(F=(K=y==null?void 0:y.shares)==null?void 0:K.orgUsersOnly)==null?void 0:F[0];I.useEffect(()=>{C==="all_users"&&V&&V.role!==void 0&&j.setOrgWideRole(V.role)},[C,V,j]);const U=D,X=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:C,onShareTypeChange:b,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(we,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(ve,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ut,{value:m,onChange:u}),e.jsx(qt,{selectedUsers:p,selectedUserObjects:S,onRemove:R,onRoleChange:M,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:f,allUsers:A,onRemove:N}),e.jsx(Yt,{usersToUpdate:g,allUsers:A,onRemove:L,getRoleOptions:Ee}),e.jsx(Qt,{existingShares:y,isInitialLoading:U,isSearching:X,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:A,currentUser:n,handleUserToggle:R,handleUserRoleChange:M,handleRemoveAccess:T,handleUpdateAccess:(_,$,q)=>{j.addUserToUpdate({id:_,currentRole:$,newRole:q})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Wt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:B,onRemoveAccess:P,allUsersToUpdate:x==="allOrgUsers"&&v!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function ht({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:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:C,isLoading:k}=Qa({enabled:(n==null?void 0:n.type)==="organization"}),[O,E]=I.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");I.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 w=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const H=(ae=(te=b==null?void 0:b.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];H&&H.role!==void 0&&j.setTenantWideRole(H.role)}else if(G==="all_tenants"){const H=(oe=(se=b==null?void 0:b.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];H&&H.role!==void 0&&j.setAllTenantsRole(H.role)}},y=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:b,isLoadingUsers:A,isErrorLoadingUsers:S,isLoadingShares:R,isErrorLoadingShares:M}=De({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),T=G=>{var se,oe;const Z=u.some(H=>H.id===G),te=h.includes(G),ae=(oe=(se=b==null?void 0:b.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(H=>H.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},N=(G,Z)=>{j.updateSelectedUserRole(G,Z)},L=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},B=G=>{j.removeUserFromRemove(G)},P=G=>{j.removeUserFromUpdate(G)},V=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},U=(G,Z)=>{O==="all_tenant_users"?j.setTenantWideRole(Z):O==="all_tenants"&&j.setAllTenantsRole(Z)},X=()=>{O==="all_tenant_users"?j.setTenantWideRole("VIEWER"):O==="all_tenants"&&j.setAllTenantsRole("VIEWER")},F=(()=>{var G,Z,te,ae;return f==="allTenants"?(Z=(G=b==null?void 0:b.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ae=(te=b==null?void 0:b.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();I.useEffect(()=>{var G,Z,te,ae;if(O==="all_tenant_users"){const se=(Z=(G=b==null?void 0:b.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(O==="all_tenants"){const se=(ae=(te=b==null?void 0:b.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[O,b,j]);const _=D.filter(G=>u.some(Z=>Z.id===G.id)),$=A||R,q=S||M,Y=()=>(n==null?void 0:n.type)==="tenant"||O==="all_tenants"?!0:v&&(O==="specific_tenant_users"||O==="all_tenant_users");return e.jsxs(e.Fragment,{children:[q&&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"})]})}),!q&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:O,onShareTypeChange:w,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(ve,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(we,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(ot,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(we,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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:y,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=C==null?void 0:C.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),Y()?e.jsx(e.Fragment,{children:O==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ut,{value:l,onChange:m}),e.jsx(qt,{selectedUsers:u,selectedUserObjects:_,onRemove:G=>T(G),onRoleChange:N,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:h,allUsers:D,onRemove:B}),e.jsx(Yt,{usersToUpdate:p,allUsers:D,onRemove:P,getRoleOptions:Ee}),e.jsx(Qt,{existingShares:b,isInitialLoading:!!$,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:D,currentUser:n,handleUserToggle:T,handleUserRoleChange:N,handleRemoveAccess:L,handleUpdateAccess:V})]}):O==="all_tenant_users"||O==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Wt,{currentUser:n,currentShare:F,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:U,onRemoveAccess:X,allUsersToUpdate:f==="allTenantUsers"&&((F==null?void 0:F.role)===void 0||g!==F.role)||f==="allTenants"&&((F==null?void 0:F.role)===void 0||x!==F.role)?{currentRole:(F==null?void 0:F.role)||"VIEWER",newRole:f==="allTenantUsers"?g:x}:null,allUsersToRemove:f==="allTenantUsers"&&(F==null?void 0:F.role)===void 0||f==="allTenants"&&(F==null?void 0:F.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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(ot,{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 Jt=()=>{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(),m=I.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]),u=I.useMemo(()=>p=>s.validateShareData(p),[]),h=I.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:m,validateShareData:u,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}};function xt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:i,onClose:c,shareTabType:l,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=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:C,isCurrentStateValid:k}=Jt(),O=n||r||o,E=()=>{var A,S,R,M;if(O)return"Updating...";if(l==="specific_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const T=u.length+h.length+p.length;return T===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${T} user${T!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(l==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const T=d.role;return g===T?"Remove Access":"Update Access"}else if(l==="all_tenants"){const T=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"Share with All Tenants";const N=T.role;return x===N?"Remove Access":"Update Access"}else if(l==="all_tenant_users"){const T=(M=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:M[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const N=T.role;return v===N?"Remove Access":"Update Access"}else if(l==="specific_tenant_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const T=u.length+h.length+p.length;return T===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${T} user${T!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},w=()=>O||!t||l==="all_tenant_users"&&!f||l==="specific_tenant_users"&&!f?!0:!k,y=()=>{const A=j();A&&C(A)&&i(A)},D=()=>{var A,S,R,M;if(l==="all_users")if(!d||d.role===void 0){const T=j();T&&C(T)&&i(T)}else{const T=d.role;if(g===T)m==null||m();else{const L=j();if(L&&C(L)){const B={...L,updateAccess:!0};i(B)}}}else if(l==="all_tenants"){const T=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0){const N=j();N&&C(N)&&i(N)}else{const N=T.role;if(x===N)m==null||m();else{const B=j();if(B&&C(B)){const P={...B,updateAccess:!0};i(P)}}}}else if(l==="all_tenant_users"){const T=(M=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:M[0];if(!T||T.role===void 0){const N=j();N&&C(N)&&i(N)}else{const N=T.role;if(v===N)m==null||m();else{const B=j();if(B&&C(B)){const P={...B,updateAccess:!0};i(P)}}}}},b=()=>{var A,S,R,M;if(l==="all_users"){if(!d||d.role===void 0)return"default";const T=d.role;return g===T?"destructive":"default"}else if(l==="all_tenants"){const T=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"default";const N=T.role;return x===N?"destructive":"default"}else if(l==="all_tenant_users"){const T=(M=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:M[0];if(!T||T.role===void 0)return"default";const N=T.role;return v===N?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:O,children:"Close"}),(l==="specific_users"||l==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(u.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||O,variant:"default",children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ge,{className:"mr-2 h-4 w-4"}),!O&&E()]})}),(l==="all_users"||l==="all_tenants"||l==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:w(),variant:b(),children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ve,{className:"mr-2 h-4 w-4"}),!O&&E()]})]})}function br({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:i,shareTabType:c,currentAllUsersShare:l}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:g}=Jt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const E=d.length+m.length+u.length;return E===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${E} user${E!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!l||l.role==="NONE")return"Share with All Users";const E=l.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,C=()=>{const E=p();E&&f(E)&&o(E)},k=()=>{if(!l||l.role==="NONE"){const E=p();E&&f(E)&&o(E)}else{const E=l.role;if(h===E){const y=p();if(y&&f(y)){const D={...y,removeAccess:!0};o(D)}}else{const y=p();if(y&&f(y)){const D={...y,updateAccess:!0};o(D)}}}},O=()=>!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||m.length>0||u.length>0)&&e.jsxs(s.Button,{onClick:C,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(Ge,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:j(),variant:O(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ge,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Xt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:i,onShare:c,onRemoveAccess:l}){var y,D,b,A;const{currentUser:d}=Le(),[m,u]=I.useState("specific_users"),[h,p]=I.useState("specific_users"),f=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),C=(D=(y=v==null?void 0:v.shares)==null?void 0:y.tenantWide)==null?void 0:D[0],k=(A=(b=j==null?void 0:j.shares)==null?void 0:b.orgUsersOnly)==null?void 0:A[0],O=()=>{if(g==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=I.useCallback(()=>{f.resetShareState(),i()},[f,i]),w=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:w?"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."})]}),w?e.jsxs(s.Tabs,{value:g,onValueChange:S=>{const R=S;f.setSelectedTab(R),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(vr,{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(ht,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>u(S),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(ht,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>u(S),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:w?g==="org"?e.jsx(xt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:l}):e.jsx(xt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:O(),currentAllUsersShare:C,onRemoveAccess:l}):e.jsx(br,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:l})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Se(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Zt(t,a,n){const{resourceType:r,resourceId:o,shareMutation:i,removeMutation:c,existingShares:l,resetUserSelections:d}=a;if(o)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=me(r,o,[{scope:"org_users_only",role:t.orgWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,o,m.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));i(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=Se(r,o,u.map(f=>{var x,v;const g=(v=(x=l==null?void 0:l.shares)==null?void 0:x.specificOrgUsers)==null?void 0:v.find(j=>j.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(g==null?void 0:g.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,o,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);i(f,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=me(r,o,[{scope:"all_tenants_only",role:t.allTenantsRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=me(r,o,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:p}=t;if(u&&u.length>0){const f=Se(r,o,u.map(g=>{var v,j;const x=(j=(v=l==null?void 0:l.shares)==null?void 0:v.specificTenantUsers)==null?void 0:j.find(C=>C.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(f=>{const g=me(r,o,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:p,role:f.newRole}]);i(g,{onSuccess:()=>{d()}})}),m&&m.length>0){const f=me(r,o,m.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.role})));i(f,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=Se(r,o,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=me(r,o,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else{const m=me(r,o,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,o,m.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));i(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=Se(r,o,u.map(f=>{var x,v;const g=(v=(x=l==null?void 0:l.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(g==null?void 0:g.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,o,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);i(f,{onSuccess:()=>{d()}})})}break}}function en(t,a,n,r){var m,u,h,p,f,g;const{resourceType:o,resourceId:i,removeMutation:c,existingShares:l,resetUserSelections:d}=r;if(i)if(t.length>0){const x=Se(o,i,t.map(v=>{var C,k;const j=(k=(C=l==null?void 0:l.shares)==null?void 0:C.specificTenantUsers)==null?void 0:k.find(O=>O.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=(u=(m=l==null?void 0:l.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(j){const C=Se(o,i,[{scope:"all_tenants_only",role:j.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(v){const j=(p=(h=l==null?void 0:l.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(j){const C=Se(o,i,[{scope:"all_tenant_users",role:j.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const j=(g=(f=l==null?void 0:l.shares)==null?void 0:f.orgUsersOnly)==null?void 0:g[0];if(j){const C=Se(o,i,[{scope:"org_users_only",role:j.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function Nr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:l}=Le(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),m=I.useCallback(()=>{r.resetUserSelections()},[r]),u=I.useCallback(p=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};Zt(p,f,l)},[t,a,n,d,m,l]),h=I.useCallback(()=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};en(o,i||"",c||"",p)},[t,a,n,d,m,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Cr(t,a,n){const{currentUser:r}=Le(),o=s.useShareManagementActions(),i=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),l=s.useShareCurrentMode(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),m=I.useCallback(()=>{o.resetUserSelections()},[o]),u=I.useCallback(p=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};Zt(p,f,r)},[t,a,n,d,m,r]),h=I.useCallback(()=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};en(i,c||"",l||"",p)},[t,a,n,d,m,i,c,l]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Sr(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 Ps(t){const[a,n]=I.useState(null),[r,o]=I.useState(null);return I.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 wr(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 pt(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=Ps(((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),m=s.useEditorStore(f=>f.isShowingVisual),u=n.sql;return{getUpdatedFrame:I.useCallback(()=>{var j;let f=u;u&&!u.includes("{{")&&(f=Sr(u),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,sql:f,customCfg:m?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(C=>C.id===n.id?x:C);return{...a,cards:v,activeCardId:wr(v,a.activeCardId)}},[n,a,m,o,i,c,l,d,t,r,u])}}function Vs(){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:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=nr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=I.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await pt((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=I.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await pt((t==null?void 0:t.accessToken)||"",x.id,a),C=v.frameObject;if(!C)return{success:!1,error:"Visual has no frame data"};const k={...C,id:s.v4()};return m(h,k,"end"),c(!0),d(k.id),u(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,m,c,d,u]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:g,getUpdatedFrame:kr().getUpdatedFrame,refetch:p.refetch}}function Er(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),[o,i]=I.useState(""),[c,l]=I.useState(""),[d,m]=I.useState(!1),[u,h]=I.useState(null),[p,f]=I.useState(!1),[g,x]=I.useState(null),[v,j]=I.useState(null),{setIsDashboardEditing:C,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:O,handleAddLibraryVisual:E}=Vs(),{resources:w,isLoading:y,isError:D,createResource:b,updateResource:A,deleteResource:S,duplicateResource:R,shareResource:M,isCreating:T,isDeleting:N,removeResourceShares:L,isSharing:B,isRemovingShares:P,isUpdatingShares:V}=rr(()=>{f(!1),x(null)},()=>{r(!1),i(""),l("")}),{handleShareSubmit:U,handleRemoveAccess:X}=Cr((u==null?void 0:u.id)||null,M,L);Le();const K=w.filter(z=>{var J,ie;return((J=z==null?void 0:z.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=z==null?void 0:z.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),F=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),_=()=>{o.trim()&&b({title:o,description:c,isPrivate:!1})},$=z=>{x(z),f(!0)},q=()=>{g&&S(g.id)},{startUpdating:Y,stopUpdating:Q,isUpdating:G}=Vt(),Z=(z,J)=>{const ie=J.title!==void 0?"title":"description";Y(z,ie),A({resourceId:z,data:J},{onSuccess:()=>{Q(z,ie)},onError:()=>{Q(z,ie)}})},te=z=>{j(z),R(z,{onSettled:()=>j(null)})},ae=z=>{O(z)},se=z=>{E(z)},oe=z=>{const J=w.find(ie=>ie.id===z);J&&A({resourceId:z,data:{isPrivate:!J.isPrivate}})},H=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),y?e.jsx(zt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:z=>l(z.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()||T,children:T?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),i(""),l("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:T,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:T,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),T?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:z=>a(z.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(us,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):K.map(z=>e.jsx(ir,{visual:z,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:$,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:H,isDeleting:N,isDuplicating:v===z.id,isTitleUpdating:G(z.id,"title"),isDescriptionUpdating:G(z.id,"description"),formatDate:F},z.id))})}),d&&u&&e.jsx(Xt,{resource:u,resourceType:ee.VISUAL,onShare:U,isSharing:B,isRemoving:P,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:X}),e.jsx(s.AlertDialog,{open:p,onOpenChange:z=>{!z&&N||(f(z),z||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:N,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),q()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:N,children:N?"Deleting...":"Delete"})]})]})})]})}function Tr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:i,onUpdateDashboard:c,onDeleteClick:l,onDuplicateDashboard:d,onShareDashboard:m,formatDate:u,onDashboardItemClick:h}){var w;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[g,x]=I.useState(!1),[v,j]=I.useState(!1),C=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);I.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(It,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{className:"h-3.5 w-3.5 text-slate-500"}),O=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),E=()=>{p(t),i(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:E,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:O()})}),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:y=>c==null?void 0:c(t.id,{title:y}),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:k()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),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:y=>y.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:y=>{y.preventDefault(),y.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:y=>{y.stopPropagation(),m(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),l(t),C(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),e.jsx("span",{children:((w=t.ownership.createdBy)==null?void 0:w.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})})})]})]},t.id)}function 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 Mr(t){const[a,n]=I.useState(""),[r,o]=I.useState(!1),[i,c]=I.useState(""),[l,d]=I.useState(""),[m,u]=I.useState(!1),[h,p]=I.useState(null),[f,g]=I.useState(!1),[x,v]=I.useState(null),[j,C]=I.useState(null),k=s.useManagementStore(H=>H.lastSelectedDashboard),O=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:w,isError:y,createResource:D,updateResource:b,deleteResource:A,duplicateResource:S,isCreating:R,isDeleting:M,isSharing:T,isRemovingShares:N,isUpdatingShares:L,shareResource:B,removeResourceShares:P}=ar(()=>{g(!1),v(null),k&&O(k)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:U}=Nr((h==null?void 0:h.id)||null,B,P),{currentUser:X}=Le(),K=E.filter(H=>{var z,J;return((z=H==null?void 0:H.title)==null?void 0:z.toLowerCase().includes(a.toLowerCase()))||((J=H==null?void 0:H.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),F=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),_=()=>{i.trim()&&D({title:i,description:l,isPrivate:!1})},$=H=>{var z;(z=t.onLoadDashboard)==null||z.call(t,H)},q=H=>{v(H),g(!0)},Y=()=>{x&&A(x.id)},Q=H=>{C(H),S(H,{onSettled:()=>C(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=Vt(),ae=(H,z)=>{const J=z.title!==void 0?"title":"description";G(H,J),b({resourceId:H,data:z},{onSuccess:()=>{Z(H,J)},onError:()=>{Z(H,J)}})},se=H=>{const z=E.find(J=>J.id===H);z&&b({resourceId:H,data:{isPrivate:!z.isPrivate}})},oe=H=>{p(H),X==null||X.type,u(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),w?e.jsx(zt,{}):y?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:H=>c(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:l,onChange:H=>d(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:_,size:"sm",className:"h-7 text-xs",disabled:!i.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),R?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:H=>n(H.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(la,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):K.map(H=>e.jsx(Tr,{dashboard:H,isDeleting:M,isDuplicating:j===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:$,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:q,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:F,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),m&&h&&e.jsx(Xt,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:T,isRemoving:N,isUpdating:L,onClose:()=>{u(!1),p(null)},onRemoveAccess:U}),e.jsx(s.AlertDialog,{open:f,onOpenChange:H=>{!H&&M||(g(H),H||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),Y()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function sn({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}=Le(),l=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Gt(a,{enabled:t}),h=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",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:m,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Mr,{onLoadDashboard:h,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Er,{})})]})})]})})}function Ar(){var K;const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(F=>F.theme);const n=s.useDashboardStore(F=>F.lenses),r=s.useDashboardStore(F=>F.selectedLensId),o=n==null?void 0:n.find(F=>F.id===r),i=s.useDashboardStore(F=>F.dashboard);s.useDashboardStore(F=>F.selectedSheetId);const c=s.useDashboardStore(F=>F.isDashboardEditing),l=s.useEditorStore(F=>F.card),d=s.useEditorStore(F=>F.selectedConnectionId),[m,u]=I.useState(!1),h=s.useDashboardStore(F=>F.isDashboardPanelOpen),p=s.useDashboardStore(F=>F.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(F=>F.filterValues),g=s.useDashboardStore(F=>F.isVisualEditing),x=s.useManagementStore(F=>F.selectedDashboard),v=(K=x==null?void 0:x.permissions)==null?void 0:K.canEdit,j=s.useDashboardStore(F=>F.showFilters);s.useDashboardStore(F=>F.showDashboardJSON);const C=s.useDashboardStore(F=>F.onSaveFunction),k=s.useDashboardStore(F=>F.actions.setShowFilters),{addFrame:O,setSelectedFrameId:E}=s.useDashboardStore(F=>F.actions),{getSelectedSheet:w,setIsDashboardEditing:y,setShowDashboardJSON:D}=s.useDashboardStore(F=>F.actions),b=w(),{tenantId:A,endUserId:S}=I.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),R=I.useMemo(()=>A||S,[A,S]),M=()=>{if(!c||!b)return;const F={dataSource:l.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},_={id:s.v4(),cards:[F],activeCardId:F.id};O(b.id,_),E(_.id)},T=()=>{y(!0)},[N,L]=I.useState(!1),B=Pt(ee.DASHBOARD);async function P(){const F=ns(i);L(!0);const _={template:F};B.mutate({resourceId:F.id,data:_},{onSuccess:()=>{L(!1),s.ue.success("Dashboard saved!")},onError:()=>{L(!1),s.ue.error("Failed to save dashboard")}})}async function V(){if(u(!0),!r||!o)return;const F=ns(i),_=JSON.stringify(F),$={...o,template:_,filterValues:f};await Ds($,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),C==null||C(F),u(!1)}if(g)return null;const U=(o==null?void 0:o.name)||i.title,X=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[X&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(ma,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:U})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Ba,{}),!g&&e.jsx(Bt,{}),c&&!g&&R&&e.jsx(Oa,{}),!g&&R&&e.jsx(Fa,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:M,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:T,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{y(!1),D(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!g&&R&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:V,size:"sm",children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),c&&!g&&R&&v&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:N,onClick:P,size:"sm",children:[N?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ws,{className:"mr-2 h-4 w-4"}),N?"Saving...":"Save"]}),!j&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>k(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(sn,{isOpen:h,onClose:()=>p(!1)})]})]})}function Lr({name:t,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:l,icon:d,showNone:m=!1}){const u=ue.useRef(null),[h,p]=ue.useState(!1),[f,g]=ue.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{u.current&&g(u.current.offsetWidth)},[]);function v(){var C;return o?"Loading...":i?"Error":n?(C=a==null?void 0:a.find(k=>k.id===n))==null?void 0:C.name:`Select ${t}`}function j(C,k){r(k),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",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(Mt,{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(C=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:k=>j(k,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function Pe({title:t,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:l=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":o?"Error":n;function p(){if(t==="Connection")return e.jsx(Ca,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ba,{className:"size-4"});if(t==="Table")return e.jsx(He,{className:"size-4"});if(t==="Model")return e.jsx(Qn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:m,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":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(Mt,{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:h,children:h})]})})]})}function g(){return e.jsx(Lr,{icon:p(),items:a,value:h,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:u==="select"?f():g()})})}function Rr({column:t}){const[a,n]=I.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:m}=s.useEditorAside(),u=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,v){var O;const j=s.createSqlGenConfig(x,l,v),C=(O=d==null?void 0:d.find(E=>E.id===c))==null?void 0:O.name;u(j);const k=s.getSql(j,s.fmt(o||""),s.fmt(r),C||"",m,i||"");k&&(h(k),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 _s({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx($e,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(ts,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function fs({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(_s,{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 Fr({onClick:t,column:a}){const n=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),i=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return l(u)||d(u)||m(u)}function l(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return o==null?void 0:o.some(h=>h.name===u.column_name)}function m(u){return i==null?void 0:i.some(h=>h.name===u.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(fs,{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(fs,{column:a})}),e.jsx(Or,{id:a.column_name,type:"column",children:e.jsx(fs,{column:a})})]})}const gs={id:"__placeholder__",role:"groupby",type:"string"},js={id:"__placeholder__",role:"groupby",type:"string"},ys={id:"__placeholder__",role:"metric",type:"number"},vs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},tn={id:"__placeholder__"},Te="droppable-group-by",Ie="droppable-metrics",Me="droppable-pivot-by",rs="sortable-group-by",ks="sortable-metrics",os="sortable-pivot-by",Es="droppable-filters",Ts="sortable-filters",Us="sortable-order-by";function Br(){const t=s.useDndStore(T=>T.insertIndex),a=s.useEditorStore(T=>{var N;return((N=T.card.queryConfig)==null?void 0:N.groupByColumns)||[]}),n=s.useEditorStore(T=>{var N;return((N=T.card.queryConfig)==null?void 0:N.metricColumns)||[]}),r=s.useEditorStore(T=>{var N;return((N=T.card.queryConfig)==null?void 0:N.filterColumns)||[]}),o=s.useEditorStore(T=>{var N;return((N=T.card.queryConfig)==null?void 0:N.orderBy)||[]}),i=s.useEditorStore(T=>{var N;return((N=T.card.queryConfig)==null?void 0:N.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:l,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:C}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),O=T=>{var B;const{active:N,over:L}=T;if(((B=N.data.current)==null?void 0:B.type)==="column"&&L){const P=L.id,V=j.find(F=>F.column_name===N.id);if(!V)return;const U=s.isNumberDataType(V.data_type),X=s.isTextDataType(V.data_type),K=s.isDateDataType(V.data_type);if(X||K){if(a.some(_=>_.id===P)){const _=a.findIndex(q=>q.id===P);c(_);const $=a.filter(q=>q.id!==gs.id);$.splice(_,0,gs),d($)}else if(L.id===Te){c(a.length);const _=[...a,gs];d(_),m(n),u(r)}}if(X||K){if(i.some(_=>_.id===P)){const _=i.findIndex(q=>q.id===P);c(_);const $=i.filter(q=>q.id!==js.id);$.splice(_,0,js),h($)}else if(L.id===Me){c(i.length);const _=[...i,js];h(_),d(a),m(n),u(r)}}if(U||X){if(n.some(_=>_.id===P)){console.log("isOverMetricSortable",P);const _=n.findIndex(q=>q.id===P);c(_);const $=n.filter(q=>q.id!==ys.id);$.splice(_,0,ys),m($)}else if(L.id===Ie){c(n.length);const _=[...n,ys];m(_),u(r),d(a),h(i)}}if(w(V)){if(r.some(_=>_.id===P)){const _=r.findIndex(q=>q.id===P);c(_);const $=r.filter(q=>q.id!==vs.id);$.splice(_,0,vs),u($)}else if(L.id===Es){c(r.length);const _=[...r,vs];u(_),m(n),d(a),h(i)}}}else d(a),m(n),u(r),h(i)};function E(T){l(T.active.id),c(null),d(a),m(n),u(r),h(i)}function w(T){return!r.some(N=>N.name===T.column_name)}function y(T,N="SUM"){const{column_name:L,data_type:B}=T,P=[...n],V=t!==null?t:n.length,U={...T,id:fe(L),name:L,label:Ke(L,N),type:B,role:"metric",aggregate:N};P.splice(V,0,U),f(P)}function D(T){const N=s.isTextDataType(T.data_type);s.isDateDataType(T.data_type);const L=[...i],B=t!==null?t:i.length;let P;N?P={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:Ve(T.column_name,"month"),granularity:"month"},L.splice(B,0,P),v(L)}function b(T){const N=s.isTextDataType(T.data_type);s.isDateDataType(T.data_type);const L=[...a],B=t!==null?t:a.length;let P;N?P={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:Ve(T.column_name,"month"),granularity:"month"},L.splice(B,0,P),p(L)}function A(T){const N=[...r],L=t!==null?t:r.length,B={...T,id:fe(T.column_name),name:T.column_name,type:T.data_type,sql:s.getDefaultFilterSql(T.data_type,C,s.fmt(T.column_name)),role:"filter"};N.splice(L,0,B),g(N)}function S(T){var P,V,U,X,K,F,_,$;const{active:N,over:L}=T,B=N.data.current;if((B==null?void 0:B.type)==="column"&&L){const q=j.find(Z=>Z.column_name===N.id);if(!q)return;const Y=s.isNumberDataType(q.data_type),Q=s.isTextDataType(q.data_type),G=s.isDateDataType(q.data_type);(Q||G)&&(L.id===Te||((P=L.data.current)==null?void 0:P.type)===rs)&&b(q),(Q||G)&&(L.id===Me||((V=L.data.current)==null?void 0:V.type)===os)?D(q):(Y||Q)&&(L.id===Ie||((U=L.data.current)==null?void 0:U.type)===ks)?(Y&&y(q),Q&&y(q,"COUNT")):w(q)&&(L.id===Es||((X=L.data.current)==null?void 0:X.type)===Ts)&&A(q)}if(L&&((K=L.data.current)==null?void 0:K.type)===rs&&a.some(q=>q.id===N.id)){const q=a.findIndex(Q=>Q.id===N.id),Y=a.findIndex(Q=>Q.id===L.id);if(q!==-1&&Y!==-1&&q!==Y){const Q=[...a],[G]=Q.splice(q,1);Q.splice(Y,0,G),p(Q)}}if(L&&((F=L.data.current)==null?void 0:F.type)===os&&i.some(q=>q.id===N.id)){const q=i.findIndex(Q=>Q.id===N.id),Y=i.findIndex(Q=>Q.id===L.id);if(q!==-1&&Y!==-1&&q!==Y){const Q=[...i],[G]=Q.splice(q,1);Q.splice(Y,0,G),v(Q)}}if(L&&((_=L.data.current)==null?void 0:_.type)===ks&&n.some(q=>q.id===N.id)){const q=n.findIndex(Q=>Q.id===N.id),Y=n.findIndex(Q=>Q.id===L.id);if(q!==-1&&Y!==-1&&q!==Y){const Q=[...n],[G]=Q.splice(q,1);Q.splice(Y,0,G),f(Q)}}if(L&&(($=L.data.current)==null?void 0:$.type)===Ts&&r.some(q=>q.id===N.id)){const q=r.findIndex(Q=>Q.id===N.id),Y=r.findIndex(Q=>Q.id===L.id);if(q!==-1&&Y!==-1&&q!==Y){const Q=[...r],[G]=Q.splice(q,1);Q.splice(Y,0,G),g(Q)}}R(T),l(null),c(null),d(a),m(n),u(r),h(i)}function R(T){const{active:N,over:L}=T,B=N.data.current;if((B==null?void 0:B.type)===Us&&L){const P=o.findIndex(U=>qe(U.columnId)===N.id),V=o.findIndex(U=>qe(U.columnId)===L.id);if(P!==-1&&V!==-1&&P!==V){const U=[...o],[X]=U.splice(P,1);U.splice(V,0,X),x(U)}}}function M(){l(null),c(null),d(a),m(n),u(r)}return{handleDragOver:O,handleDragEnd:S,handleDragStart:E,handleDragCancel:M,sensors:k}}function fe(t){return`${t}-${s.v4()}`}function Ke(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 qe(t){return`${Us}-${t}`}function Ve(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 zr({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(N=>N.sqlGen),i=s.useEditorStore(N=>N.isDevMode),c=s.useEditorStore(N=>N.selectedConnectionId),l=s.useEditorStore(N=>{var L,B;return(B=(L=N.card)==null?void 0:L.queryConfig)==null?void 0:B.metricColumns});s.useEditorStore(N=>{var L,B;return(B=(L=N.card)==null?void 0:L.queryConfig)==null?void 0:B.groupByColumns});const d=s.useEditorStore(N=>N.selectedDatabaseName),m=s.useEditorStore(N=>N.selectedSchemaName),u=s.useEditorStore(N=>N.selectedTableName),h=s.useEditorStore(N=>N.selectedDatamodelId),p=s.useDashboardStore(N=>N.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:C,setSqlGen:k,setIsShowingVisual:O}=s.useEditorActions(),{connectionType:E,modelItems:w,selectedDatamodelName:y}=s.useEditorAside();function D(N){var L;if(i){const B=s.createSqlGenConfig(N,o);k(B);const P=(L=w==null?void 0:w.find(U=>U.id===h))==null?void 0:L.name,V=s.getSql(B,s.fmt(t),s.fmt(a),P||"",E,d||"");V&&(j(V),C(!0))}if(!i){if(s.isTextDataType(N.data_type))if(l&&l.length>0){const B={...N,role:"groupby",id:fe(N.column_name),name:N.column_name,type:N.data_type};v(B)}else{const B={...N,role:"metric",id:fe(N.column_name),name:N.column_name,label:Ke(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};x(B)}if(s.isDateDataType(N.data_type)){const B={...N,role:"groupby",id:fe(N.column_name),name:N.column_name,type:N.data_type,label:Ve(N.column_name,"month"),granularity:"month"};v(B)}if(s.isNumberDataType(N.data_type)){const B={...N,role:"metric",id:fe(N.column_name),name:N.column_name,label:Ke(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};x(B)}}}function b(N){N===!0&&(u||y)&&c?(f({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(y),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:u||"",datamodelName:s.resolveDatamodelName(y),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function A(){const N=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:E,databaseName:d||""});O(!1);const L=E==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;j(L),C(!0)}function S(){const N=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${N}`),C(!0)}function R(){return(p==null?void 0:p.find(N=>N.connectionId===c&&(N.tableName===u||N.datamodelName===y)))!==void 0}function M(N){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(N),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_s,{column:N}),e.jsx("span",{children:N.column_name})]}),e.jsx("div",{onClick:L=>L.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(N.data_type)&&e.jsx(Rr,{column:N})})]}):e.jsx(Fr,{onClick:D,column:N})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${R()?"Remove from":"Add to"} Assistant Scope`,pressed:R(),onPressedChange:b,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":R(),"text-muted-foreground":!R()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:A,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(ga,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((N,L)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},L))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:T()}),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(N=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:M(N)},N.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function nn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),i=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),l=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),m=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:C,isConnectionsLoading:k,isModelsLoading:O,isConnectionsError:E,isModelsError:w,isDatabasesLoadingOrFetching:y,isDatabaseError:D,isSchemaLoadingOrFetching:b,isSchemaError:A,isColumnsError:S,isColumnsLoadingOrFetching:R,isTableLoadingOrFetching:M,isTableError:T,connectionType:N,isNonDbConnection:L,refetchDatabases:B,refetchModels:P,refetchSchemas:V,refetchTables:U,refetchColumns:X,refetchConnections:K,handleConnectionChange:F,handleDatabaseChange:_,handleSchemaChange:$,handleDatamodelChange:q,handleTableChange:Y,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,C):e.jsx(zr,{schemaName:G,tableName:Q,columns:C,status:R?"Loading...":S?"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(""),h(ne)}function H(){if(!r||N==="S3"||N==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:B,showNone:!0,onChange:_,isError:D,isLoading:y,items:v,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!L&&(!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||N==="S3"||N==="API")return null;if(!c||c==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:q,isError:w,isLoading:O,items:g,value:i||"",title:"Model",type:"combobox"})}function ie(){return!r||N==="S3"||N==="API"||!c||c==="none"?null:e.jsx(Pe,{refetch:V,onChange:$,isError:A,isLoading:b,items:x,value:l||"",title:"Schema",type:"combobox"})}function be(){function ne(){let le=!1;return N==="API"?(le=!1,le):((N==="S3"||r&&c&&c!=="none"&&l)&&(le=!0),le)}return ne()?e.jsx(Pe,{refetch:U,onChange:Y,isError:T,items:j,isLoading:M,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(Pe,{refetch:K,items:f,title:"Connection",value:r||"",onChange:F,isLoading:k,isError:E,type:"combobox",connectionTooltip:((ke=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),H(),z(),J(),ie(),be()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,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(ya,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function an({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=I.useState(!1),c=I.useRef(null),l=I.useRef(!1);function d(){t&&!l.current&&navigator.clipboard.writeText(t)}function m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function u(){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 h(){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:m,onMouseUp:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function rn({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(an,{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(aa,{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(ua,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function on({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(Et,{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(rn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var ln={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ft=I.createContext&&I.createContext(ln),Pr=["attr","size","title"];function Vr(t,a){if(t==null)return{};var n=_r(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 _r(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 is(){return is=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},is.apply(this,arguments)}function gt(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 ls(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?gt(Object(n),!0).forEach(function(r){Ur(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ur(t,a,n){return a=qr(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function qr(t){var a=$r(t,"string");return typeof a=="symbol"?a:a+""}function $r(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 cn(t){return t&&t.map((a,n)=>I.createElement(a.tag,ls({key:n},a.attr),cn(a.child)))}function Re(t){return a=>I.createElement(Yr,is({attr:ls({},t.attr)},a),cn(t.child))}function Yr(t){var a=n=>{var{attr:r,size:o,title:i}=t,c=Vr(t,Pr),l=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),I.createElement("svg",is({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:ls(ls({color:t.color||n.color},n.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),i&&I.createElement("title",null,i),t.children)};return ft!==void 0?I.createElement(ft.Consumer,null,n=>a(n)):a(ln)}function Gr(t){return Re({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 dn(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:m}=s.useEditorActions(),u=I.useRef(),h=I.useRef({}),p=r.cards.find(x=>x.id===i),f=I.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]);I.useEffect(()=>{if(i&&o.id&&o.id!==i){if(u.current&&c){const x=u.current.getModel();x&&(h.current[o.id]=x);let v=h.current[i];if(!v){const j=f();v=c.editor.createModel(j,t),h.current[i]=v}u.current.setModel(v)}d(i,o),m(!0)}},[i,o,d,c,m,t,f]),I.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]),I.useEffect(()=>{const x=u.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return l(),!1})},[c,l,o]);function g(x,v){if(u.current=x,!h.current[o.id]){const j=x.getModel(),C=f();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(C,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function Hr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=dn("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}=dn("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 Kr({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function qs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(l=>l.frame);const n=s.useEditorStore(l=>l.card);Ps(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(l=>l.selectedSchemaName),s.useEditorStore(l=>l.selectedDatamodelId),s.useEditorStore(l=>l.selectedDatabaseName),s.useEditorStore(l=>l.selectedTableName),s.useEditorStore(l=>l.selectedConnectionId),s.useEditorStore(l=>l.isShowingVisual),n.sql;const r=s.useEditorStore(l=>l.onSave),{getUpdatedFrame:o}=Vs();function i(){const l=o();r==null||r(l)}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Wr(){const t=s.useQueryClient(),[a,n]=I.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:i}=Vs(),c=s.useSelectedVisual(),l=or(),d=()=>{const m=i();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),l.mutate({visualId:c.id,data:{frameObject:m}},{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(ws,{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:m}=r;d&&m&&n.setQueryData(d,m)}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 ms(){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:m,setCardPreferences:u,updateDataSource:h,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&&h(s.EMPTY_DATA_SOURCE),c(""),l({}),p(),f(void 0),d(""),m(""),u({}),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 Jr(){const t=s.useQueryClient(),[a,n]=I.useState(!1),[r,o]=I.useState(!1);s.useEditorStore(U=>U.frame);const i=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.isShowingVisual),s.useEditorStore(U=>U.selectedConnectionId),s.useEditorStore(U=>U.tempQueryData),s.useEditorStore(U=>U.selectedDatabaseName),s.useEditorStore(U=>U.selectedDatamodelId),s.useEditorStore(U=>U.selectedSchemaName);const c=s.useEditorStore(U=>U.showAIDialog);s.useEditorStore(U=>U.selectedTableName);const l=s.useEditorStore(U=>{var X;return(X=U==null?void 0:U.card)==null?void 0:X.sql}),d=s.useEditorStore(U=>{var X;return(X=U==null?void 0:U.card)==null?void 0:X.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:p,setTempQueryData:f,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:C,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(U=>U.onSave),s.useEditorStore(U=>U.onClose),s.useEditorStore(U=>U.actions.setSqlGen);const O=s.useEditorStore(U=>U.runSql),E=s.useEditorStore(U=>U.actions.setRunSql),w=s.useEditorStore(U=>U.actions.setIsSqlRunning),{data:y,isLoading:D,isFetching:b,isSuccess:A,isError:S,error:R,queryKey:M,refetch:T,errorMessage:N}=s.useDashboardCardQuery(i);I.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:U}=s.getKeys(y.records);h(U)}},[y,h,g]),I.useEffect(()=>{(D||b)&&w(!0),(S||A)&&w(!1),S&&(h([]),g(""))},[D,b,y,g,S,A,w,h,R]),I.useEffect(()=>{O&&(t.getQueryData(M)||T(),E(!1))},[O,T,E,M,t]);async function L(){const U=`Can you help me debug this query in the current table scope?
|
|
416
|
+
*/const Ma=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ns(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=>Ot(c))}})}})}}function Ot(t){return{...t,customCfg:Aa(t.customCfg),data:[]}}function Aa(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 La(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 Ds(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 Ra(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[l,d]=I.useState(!1),[m,u]=I.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:f}=s.useSemaphorContext();async function j(){d(!0);const x=ns(h),y=await La(t,x,p,f==null?void 0:f.accessToken);y&&(i([...o||[],y]),c(y.id),u(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:u,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange: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:j,disabled:l,children:l?"Creating...":"Add"})})]})]})}function Fa(){const[t,a]=I.useState(!1),n=s.useDashboardStore(u=>u.lenses),r=s.useDashboardStore(u=>u.selectedLensId),{setLenses:o,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function l(u){i(u)}async function d(u){if(await Oa(u,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(f=>f.id!==u);o(p||[]),i("original")}}async function m(u){const h=n==null?void 0:n.map(j=>j.id===u.id?{...j,isDefault:!u.isDefault}:{...j,isDefault:!1});o(h||[]);const p={...u,isDefault:!u.isDefault};await Ds(p,c==null?void 0:c.accessToken);const f=n==null?void 0:n.find(j=>j.isDefault);if(f&&f.id!==u.id){const j={...f,isDefault:!1};await Ds(j,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(ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:l,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(u=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(u)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Rt(){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 Ft(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const l=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(l,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=u;const p=`${o}-${new Date().toISOString()}.pdf`;h.download=p,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function Ba({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 Ft()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className: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 ut=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=za(),[l,d]=I.useState(""),[m,u]=I.useState(ut[0].value),[h,p]=I.useState("06:00"),[f,j]=I.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=>{j(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:ut,value:m,onValueChange:x=>u(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:h,onChange:x=>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:m,time:h,subject:f}),p("00:00"),d(""),j("")},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(Tt,{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(mt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Jn,{className:"size-3.5"})}),e.jsx(mt,{tooltip:`${x.endUserEmail}`,children:e.jsx(ja,{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 mt=({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]=I.useState("idle"),[n,r]=I.useState(""),[o,i]=I.useState(null),c=s.useDashboardStore(k=>k.authToken),l=s.useDashboardStore(k=>k.dashboard.id),d=s.useDashboardStore(k=>k.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:l,endUserId:m},{data:p,isLoading:f,isError:j,isFetching:x,refetch:y}=s.useQuery({queryKey:["subscriptions",l,m],queryFn:()=>s.getRequest(u,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!l&&!!m});async function g({email:k,subject:R,frequency:T,time:w}){const{authToken:v,...D}=Rt(),b=Intl.DateTimeFormat().resolvedOptions().timeZone,A={email:k,frequency:T,time:w,timezone:b,endUserId:m,endUserEmail:k,subject:R||d||"Scheduled Dashboard",dashboardId:l,dashboardParams:D};a("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(S,(v==null?void 0:v.accessToken)||"",{...A});a("success"),r(""),y(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function C(k){const R="https://semaphor.cloud/api/v1/subscriptions/delete";i(k);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:k}),y(),setTimeout(()=>{i(null)},2e3)}catch(T){console.error(T),i(null),a("error"),r(T.message)}}return{data:p,isLoading:f,isFetching:x,isError:j,isDeleting:o,refetch:y,handleScheduleSubscription:g,handleDeleteSubscription:C,status:t,error:n}}function be(){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 zt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Pa=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)},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};console.log("data",r);const 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()},Ua=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,{})},$a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Ya=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()},Ga=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)},Ha=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function Qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ka(t,a,n,r,o){const{authToken:i}=s.useSemaphorContext(),{currentUser:c}=be();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Pa((i==null?void 0:i.accessToken)||"",t),enabled:!!(i!=null&&i.accessToken)&&!!c})}function Wa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Le({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 Pt(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Le({mutationFn:({resourceId:r,data:o})=>_a((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Le({mutationFn:o=>Ua((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 Xa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Le({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 Za(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Le({mutationFn:({resourceType:n,resourceId:r,data:o})=>$a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function er(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Le({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ya((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 sr(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ga((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function tr(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>Ha((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 nr(t,a){return tr(ee.VISUAL,t,a)}function Vt(){const[t,a]=I.useState(new Map),n=I.useCallback((i,c)=>{a(l=>{const d=new Map(l),m=new Set(d.get(i)||[]);return c?m.add(c):(m.add("title"),m.add("description")),d.set(i,m),d})},[]),r=I.useCallback((i,c)=>{a(l=>{const d=new Map(l),m=new Set(d.get(i)||[]);return c?m.delete(c):m.clear(),m.size===0?d.delete(i):d.set(i,m),d})},[]),o=I.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 _t(t,a,n){var h;const r=Ka(t),o=Wa(t,n),i=Pt(t),c=Ja(t,a),l=Xa(t),d=Za(),m=er(),u={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[u[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:i.mutate,deleteResource:c.mutate,duplicateResource:l.mutate,shareResource:d.mutate,removeResourceShares:m.mutate,isCreating:o.isPending,isUpdating:i.isPending,isDeleting:c.isPending,isDuplicating:l.isPending,isSharing:d.isPending,isRemovingShares:m.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function ar(t,a){return _t(ee.DASHBOARD,t,a)}function rr(t,a){return _t(ee.VISUAL,t,a)}function or(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Le({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 ir({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:i,onEditVisual:c,onUpdateVisual:l,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:u,formatDate:h}){var w;const{selectVisual:p}=s.useManagementActions(),f=s.useIsVisualSelected(t.id),j=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen),[x,y]=I.useState(!1),[g,C]=I.useState(!1);I.useEffect(()=>{n?(y(!0),C(!0)):g&&(y(!1),C(!1))},[n,g]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(It,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(De,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),T=()=>{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:T,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:R()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:v=>l==null?void 0:l(t.id,{title:v}),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:k()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:v=>l==null?void 0:l(t.id,{description:v}),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:v=>{v.stopPropagation(),i(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:y,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:v=>v.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),m(t.id)},disabled: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:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Na,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),u(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),d(t),j(!1)},className:"text-destructive",disabled: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(De,{className:"h-3 w-3"}),e.jsx("span",{children:((w=t.ownership.createdBy)==null?void 0:w.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 Ut({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 as({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:i=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,l=n.filter(m=>m.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(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function qt({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(as,{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 Yt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),i=l=>{const d=a.find(m=>m.id===l);return(d==null?void 0:d.name)||"Unknown User"},c=l=>{const d=o.find(m=>m.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(ve,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(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 Gt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=I.useRef(null);return I.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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function lr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Ht(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function cr(t,a,n){const r=Ht(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 dr({user:t}){return Ht(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 ur({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:i}){if(!(a!=null&&a.role))return null;const c=lr((r==null?void 0:r.type)||""),l=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),m=d?d.newRole:a==null?void 0:a.role,u=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(as,{currentRole:m,onRoleChange:h=>{i(t.id,a.role,h)},roleOptions:u,disabled:!c,allowDropdown:c,className:l?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:pe(m,u)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function mr({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(He,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function hr({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 xr({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||[],m=c.orgWide||[],u=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[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 g,C;const j=((g=a.find(k=>k.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(k=>k.id===p.orgUserId))==null?void 0:C.type)||"",y=pe(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:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},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 g,C;const j=((g=a.find(k=>k.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((C=a.find(k=>k.id===p.tenantUserId))==null?void 0:C.type)||"",y=pe(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:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},f)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((p,f)=>{const j=pe(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:j})]},f)})})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((p,f)=>{const j=pe(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:j})]},f)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((p,f)=>{const j=pe(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:j})]},f)})})]}),!l.length&&!d.length&&!m.length&&!u.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],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,m)=>{var f,j;const u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.name)||"Unknown User",h=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=pe(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),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,m)=>{const u=pe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},m)})})]}),!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 m=((p=a.find(j=>j.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",u=((f=a.find(j=>j.id===l.tenantUserId))==null?void 0:f.type)||"",h=pe(l.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),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 m=pe(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:m})]},d)})})]}),!i.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function pr({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 fr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:i,selectedUser:c,roleOptions:l,currentUser:d,usersToUpdate:m,handleUserToggle:u,handleRemoveAccess:h,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?u(t.id):h(t.id):u(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(dr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(as,{currentRole:a==null?void 0:a.role,onRoleChange:j=>p(t.id,a.role,j),roleOptions:l,disabled:!1,allowDropdown:!0}):e.jsx(ur,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>l,handleUpdateAccess:p}),i&&!o&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(as,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>f(t.id,j),roleOptions:l,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(mr,{hasAccess:r,isUserRemoving:n,isSelected:i,hasAccessFromAPI:o}),e.jsx(hr,{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:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(T=>{const w=u.some(D=>D.id===T),v=h.includes(T);w?j.removeSelectedUser(T):v?j.removeUserFromRemove(T):j.addSelectedUser({id:T,role:"VIEWER"})}),y=l||j.updateSelectedUserRole,g=d||j.addUserToRemove,C=m||((T,w,v)=>{j.addUserToUpdate({id:T,currentRole:w,newRole:v})}),k=o,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(xr,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:i})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{u.length===k.length?j.setSelectedUsers([]):j.setSelectedUsers(k.map(T=>({id:T.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:u.length===k.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(pr,{isInitialLoading:a,isSearching:n,searchQuery:f,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(T=>{const w=t?cr(T,t,i):void 0,v=R.includes(T.id),D=!!w,b=D&&!v,A=u.some(M=>M.id===T.id),S=u.find(M=>M.id===T.id),O=r(T.type);return e.jsx(fr,{user:T,userShare:w,isUserRemoving:v,hasAccess:b,hasAccessFromAPI:D,isSelected:A,selectedUser:S,roleOptions:O,currentUser:i,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:C,handleUserRoleChange:y},T.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(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(De,{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 Ee=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function gr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:i=!1,isUpdating:c=!1,isRemoving:l=!1}){const d=s.useShareCurrentMode(),m=Ee().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),u=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:u,p=a.role!=="NONE"&&!i&&(!o||o.newRole===u),f=o!==null&&o.newRole!==u,j=i,x=u==="NONE"||!u,y=C=>{switch(C){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(Da,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=C=>{r(u,C)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",f&&!j&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":j||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(ve,{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"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:m.map(C=>e.jsxs(s.Button,{variant:h===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(C.value),disabled:n||c||l,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Wt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:i,onRemoveAccess:c,allUsersToUpdate:l,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:m(a.role)}:{role:"NONE"},p=l?{currentRole:m(l.currentRole),newRole:m(l.newRole)}:null,f=(x,y)=>{i(x,y)},j=()=>{c()};return e.jsx(gr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:f,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}const jr=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 yr(t={}){var i,c,l;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=s.useQuery({queryKey:["unified-users",t],queryFn:()=>jr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,m)=>m instanceof Error&&m.message.includes("401")||m instanceof Error&&m.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((i=o.data)==null?void 0:i.users)||[],userContext:(c=o.data)==null?void 0:c.userContext,total:((l=o.data)==null?void 0:l.total)||0,isLoading:o.isLoading,isError:o.isError,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function ke(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:i}=t,c=I.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&i?{tenantId:i}:{}}),[a,o,i]),{users:l,isLoading:d,isError:m}=yr(c),u=sr(r,n);return{allUsers:l,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:u.data,isLoadingShares:u.isLoading,isErrorLoadingShares:u.isError,isFetchingShares:u.isFetching}}function vr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:i=!1,isRemoving:c=!1}){var K,$;const l=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:u,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),f=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[C,k]=I.useState("specific_users"),R=()=>{if(l==="org")return"organization";if(l==="tenant")return"tenant"},T=()=>{if(l==="tenant"&&d)return d},{allUsers:w,existingShares:v,isLoadingUsers:D}=ke({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:T()});I.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,C]);const b=F=>{var _,Y;const U=F;if(k(U),r==null||r(U),g.setCurrentContext("org-tab"),U==="specific_users")g.setCurrentMode("specificOrgUsers");else if(U==="all_users"){g.setCurrentMode("allOrgUsers");const Q=(Y=(_=v==null?void 0:v.shares)==null?void 0:_.orgUsersOnly)==null?void 0:Y[0];Q&&Q.role!==void 0&&g.setOrgWideRole(Q.role)}},A=w.filter(F=>F.name.toLowerCase().includes(m.toLowerCase())||F.email.toLowerCase().includes(m.toLowerCase())),S=w.filter(F=>p.some(U=>U.id===F.id)),O=F=>{var Q,G;const U=p.some(Z=>Z.id===F),_=f.includes(F),Y=(G=(Q=v==null?void 0:v.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===F);U?g.removeSelectedUser(F):_?g.removeUserFromRemove(F):Y||g.addSelectedUser({id:F,role:"VIEWER"})},M=(F,U)=>{g.updateSelectedUserRole(F,U)},E=F=>{g.addUserToRemove(F),g.removeSelectedUser(F)},N=F=>{g.removeUserFromRemove(F)},L=F=>{g.removeUserFromUpdate(F)},B=(F,U)=>{g.setOrgWideRole(U)},P=()=>{g.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=($=(K=v==null?void 0:v.shares)==null?void 0:K.orgUsersOnly)==null?void 0:$[0];I.useEffect(()=>{C==="all_users"&&V&&V.role!==void 0&&g.setOrgWideRole(V.role)},[C,V,g]);const q=D,X=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:C,onShareTypeChange:b,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(De,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(ve,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ut,{value:m,onChange:u}),e.jsx(qt,{selectedUsers:p,selectedUserObjects:S,onRemove:O,onRoleChange:M,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:f,allUsers:A,onRemove:N}),e.jsx(Yt,{usersToUpdate:j,allUsers:A,onRemove:L,getRoleOptions:Ee}),e.jsx(Qt,{existingShares:v,isInitialLoading:q,isSearching:X,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:A,currentUser:n,handleUserToggle:O,handleUserRoleChange:M,handleRemoveAccess:E,handleUpdateAccess:(F,U,_)=>{g.addUserToUpdate({id:F,currentRole:U,newRole:_})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Wt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:B,onRemoveAccess:P,allUsersToUpdate:x==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function ht({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:m}=s.useShareSearchWithDebounce(),u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:C,isLoading:k}=Qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,T]=I.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");I.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),g.setCurrentMode("specificTenantUsers")):(g.setCurrentContext("tenant-tab"),g.setCurrentMode("allTenants"))},[g,n==null?void 0:n.type]);const w=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"?(g.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(g.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&g.setSelectedTenant(n.tenantId))):(g.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?g.setCurrentMode("allTenantUsers"):G==="all_tenants"&&g.setCurrentMode("allTenants")),G==="all_tenant_users"){const H=(ae=(te=b==null?void 0:b.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];H&&H.role!==void 0&&g.setTenantWideRole(H.role)}else if(G==="all_tenants"){const H=(oe=(se=b==null?void 0:b.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];H&&H.role!==void 0&&g.setAllTenantsRole(H.role)}},v=G=>{g.setSelectedTenant(G)},{allUsers:D,existingShares:b,isLoadingUsers:A,isErrorLoadingUsers:S,isLoadingShares:O,isErrorLoadingShares:M}=ke({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:y}),E=G=>{var se,oe;const Z=u.some(H=>H.id===G),te=h.includes(G),ae=(oe=(se=b==null?void 0:b.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(H=>H.tenantUserId===G);Z?g.removeSelectedUser(G):te?g.removeUserFromRemove(G):ae||g.addSelectedUser({id:G,role:"VIEWER"})},N=(G,Z)=>{g.updateSelectedUserRole(G,Z)},L=G=>{g.addUserToRemove(G),g.removeSelectedUser(G)},B=G=>{g.removeUserFromRemove(G)},P=G=>{g.removeUserFromUpdate(G)},V=(G,Z,te)=>{g.addUserToUpdate({id:G,currentRole:Z,newRole:te})},q=(G,Z)=>{R==="all_tenant_users"?g.setTenantWideRole(Z):R==="all_tenants"&&g.setAllTenantsRole(Z)},X=()=>{R==="all_tenant_users"?g.setTenantWideRole("VIEWER"):R==="all_tenants"&&g.setAllTenantsRole("VIEWER")},$=(()=>{var G,Z,te,ae;return f==="allTenants"?(Z=(G=b==null?void 0:b.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:f==="allTenantUsers"?(ae=(te=b==null?void 0:b.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();I.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=b==null?void 0:b.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&g.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=b==null?void 0:b.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&g.setAllTenantsRole(se.role)}},[R,b,g]);const F=D.filter(G=>u.some(Z=>Z.id===G.id)),U=A||O,_=S||M,Y=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[_&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!_&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:w,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(ve,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(De,{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(ot,{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(De,{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:y||"",onValueChange:v,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=C==null?void 0:C.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),Y()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ut,{value:l,onChange:m}),e.jsx(qt,{selectedUsers:u,selectedUserObjects:F,onRemove:G=>E(G),onRoleChange:N,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:h,allUsers:D,onRemove:B}),e.jsx(Yt,{usersToUpdate:p,allUsers:D,onRemove:P,getRoleOptions:Ee}),e.jsx(Qt,{existingShares:b,isInitialLoading:!!U,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:D,currentUser:n,handleUserToggle:E,handleUserRoleChange:N,handleRemoveAccess:L,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Wt,{currentUser:n,currentShare:$,isSharing:o,isUpdating:i,isRemoving:c,onUpdateAccess:q,onRemoveAccess:X,allUsersToUpdate:f==="allTenantUsers"&&(($==null?void 0:$.role)===void 0||j!==$.role)||f==="allTenants"&&(($==null?void 0:$.role)===void 0||x!==$.role)?{currentRole:($==null?void 0:$.role)||"VIEWER",newRole:f==="allTenantUsers"?j:x}:null,allUsersToRemove:f==="allTenantUsers"&&($==null?void 0:$.role)===void 0||f==="allTenants"&&($==null?void 0:$.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ot,{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 Jt=()=>{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(),m=I.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]),u=I.useMemo(()=>p=>s.validateShareData(p),[]),h=I.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:m,validateShareData:u,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:i,orgWideRole:c,allTenantsRole:l,tenantWideRole:d}};function xt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:i,onClose:c,shareTabType:l,currentAllUsersShare:d,onRemoveAccess:m}){const u=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const f=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:C,isCurrentStateValid:k}=Jt(),R=n||r||o,T=()=>{var A,S,O,M;if(R)return"Updating...";if(l==="specific_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const E=u.length+h.length+p.length;return E===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(l==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const E=d.role;return j===E?"Remove Access":"Update Access"}else if(l==="all_tenants"){const E=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"Share with All Tenants";const N=E.role;return x===N?"Remove Access":"Update Access"}else if(l==="all_tenant_users"){const E=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const N=E.role;return y===N?"Remove Access":"Update Access"}else if(l==="specific_tenant_users"){if(u.length===0&&h.length===0&&p.length===0)return"Select users to share with";const E=u.length+h.length+p.length;return E===0?"Select users to share with":u.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:p.length>0&&u.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},w=()=>R||!t||l==="all_tenant_users"&&!f||l==="specific_tenant_users"&&!f?!0:!k,v=()=>{const A=g();A&&C(A)&&i(A)},D=()=>{var A,S,O,M;if(l==="all_users")if(!d||d.role===void 0){const E=g();E&&C(E)&&i(E)}else{const E=d.role;if(j===E)m==null||m();else{const L=g();if(L&&C(L)){const B={...L,updateAccess:!0};i(B)}}}else if(l==="all_tenants"){const E=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0){const N=g();N&&C(N)&&i(N)}else{const N=E.role;if(x===N)m==null||m();else{const B=g();if(B&&C(B)){const P={...B,updateAccess:!0};i(P)}}}}else if(l==="all_tenant_users"){const E=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!E||E.role===void 0){const N=g();N&&C(N)&&i(N)}else{const N=E.role;if(y===N)m==null||m();else{const B=g();if(B&&C(B)){const P={...B,updateAccess:!0};i(P)}}}}},b=()=>{var A,S,O,M;if(l==="all_users"){if(!d||d.role===void 0)return"default";const E=d.role;return j===E?"destructive":"default"}else if(l==="all_tenants"){const E=(S=(A=a==null?void 0:a.shares)==null?void 0:A.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"default";const N=E.role;return x===N?"destructive":"default"}else if(l==="all_tenant_users"){const E=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[0];if(!E||E.role===void 0)return"default";const N=E.role;return y===N?"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:(u.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(He,{className:"mr-2 h-4 w-4"}),!R&&T()]})}),(l==="all_users"||l==="all_tenants"||l==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:w(),variant:b(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ve,{className:"mr-2 h-4 w-4"}),!R&&T()]})]})}function br({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:i,shareTabType:c,currentAllUsersShare:l}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),u=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:f,isCurrentStateValid:j}=Jt(),x=a||n||r,y=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&u.length===0)return"Select users to share with";const T=d.length+m.length+u.length;return T===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${T} user${T!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&u.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Update access for ${u.length} user${u.length!==1?"s":""}`:`Update access for ${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 h===T?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!j,C=()=>{const T=p();T&&f(T)&&o(T)},k=()=>{if(!l||l.role==="NONE"){const T=p();T&&f(T)&&o(T)}else{const T=l.role;if(h===T){const v=p();if(v&&f(v)){const D={...v,removeAccess:!0};o(D)}}else{const v=p();if(v&&f(v)){const D={...v,updateAccess:!0};o(D)}}}},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||m.length>0||u.length>0)&&e.jsxs(s.Button,{onClick:C,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(He,{className:"mr-2 h-4 w-4"}),!x&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:g(),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(He,{className:"mr-2 h-4 w-4"}),!x&&y()]})]})}function Xt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:i,onShare:c,onRemoveAccess:l}){var v,D,b,A;const{currentUser:d}=be(),[m,u]=I.useState("specific_users"),[h,p]=I.useState("specific_users"),f=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:y}=ke({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=ke({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),C=(D=(v=y==null?void 0:y.shares)==null?void 0:v.tenantWide)==null?void 0:D[0],k=(A=(b=g==null?void 0:g.shares)==null?void 0:b.orgUsersOnly)==null?void 0:A[0],R=()=>{if(j==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=I.useCallback(()=>{f.resetShareState(),i()},[f,i]),w=(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(He,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:w?"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."})]}),w?e.jsxs(s.Tabs,{value:j,onValueChange:S=>{const O=S;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(vr,{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(ht,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>u(S),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(ht,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>u(S),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:w?j==="org"?e.jsx(xt,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:l}):e.jsx(xt,{resource:t,existingShares:y,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:R(),currentAllUsersShare:C,onRemoveAccess:l}):e.jsx(br,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:i,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:l})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function we(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Zt(t,a,n){const{resourceType:r,resourceId:o,shareMutation:i,removeMutation:c,existingShares:l,resetUserSelections:d}=a;if(o)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const m=me(r,o,[{scope:"org_users_only",role:t.orgWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,o,m.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));i(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=we(r,o,u.map(f=>{var x,y;const j=(y=(x=l==null?void 0:l.shares)==null?void 0:x.specificOrgUsers)==null?void 0:y.find(g=>g.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,o,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);i(f,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const m=me(r,o,[{scope:"all_tenants_only",role:t.allTenantsRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const m=me(r,o,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h,tenantId:p}=t;if(u&&u.length>0){const f=we(r,o,u.map(j=>{var y,g;const x=(g=(y=l==null?void 0:l.shares)==null?void 0:y.specificTenantUsers)==null?void 0:g.find(C=>C.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(f=>{const j=me(r,o,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:p,role:f.newRole}]);i(j,{onSuccess:()=>{d()}})}),m&&m.length>0){const f=me(r,o,m.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));i(f,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const m=we(r,o,[{scope:"all_tenant_users",role:"VIEWER"}]);c(m,{onSuccess:()=>{d()}})}else if(t.updateAccess){const m=me(r,o,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else{const m=me(r,o,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);i(m,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:m,usersToRemove:u,usersToUpdate:h}=t;if(m&&m.length>0){const p=me(r,o,m.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));i(p,{onSuccess:()=>{d()}})}if(u&&u.length>0){const p=we(r,o,u.map(f=>{var x,y;const j=(y=(x=l==null?void 0:l.shares)==null?void 0:x.specificTenantUsers)==null?void 0:y.find(g=>g.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const f=me(r,o,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);i(f,{onSuccess:()=>{d()}})})}break}}function en(t,a,n,r){var m,u,h,p,f,j;const{resourceType:o,resourceId:i,removeMutation:c,existingShares:l,resetUserSelections:d}=r;if(i)if(t.length>0){const x=we(o,i,t.map(y=>{var C,k;const g=(k=(C=l==null?void 0:l.shares)==null?void 0:C.specificTenantUsers)==null?void 0:k.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:y=>{console.error("Remove access failed:",y)}})}else{const x=a==="tenant"&&n==="allTenants",y=a==="tenant"&&n==="allTenantUsers";if(x){const g=(u=(m=l==null?void 0:l.shares)==null?void 0:m.allTenantsOnly)==null?void 0:u[0];if(g){const C=we(o,i,[{scope:"all_tenants_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(y){const g=(p=(h=l==null?void 0:l.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(g){const C=we(o,i,[{scope:"all_tenant_users",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const g=(j=(f=l==null?void 0:l.shares)==null?void 0:f.orgUsersOnly)==null?void 0:j[0];if(g){const C=we(o,i,[{scope:"org_users_only",role:g.role}]);c(C,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function Nr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:l}=be(),{existingShares:d}=ke({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),m=I.useCallback(()=>{r.resetUserSelections()},[r]),u=I.useCallback(p=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};Zt(p,f,l)},[t,a,n,d,m,l]),h=I.useCallback(()=>{if(!t)return;const p={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};en(o,i||"",c||"",p)},[t,a,n,d,m,o,i,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Cr(t,a,n){const{currentUser:r}=be(),o=s.useShareManagementActions(),i=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),l=s.useShareCurrentMode(),{existingShares:d}=ke({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),m=I.useCallback(()=>{o.resetUserSelections()},[o]),u=I.useCallback(p=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:m};Zt(p,f,r)},[t,a,n,d,m,r]),h=I.useCallback(()=>{if(!t)return;const p={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:m};en(i,c||"",l||"",p)},[t,a,n,d,m,i,c,l]);return{handleShareSubmit:u,handleRemoveAccess:h}}function Sr(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 Ps(t){const[a,n]=I.useState(null),[r,o]=I.useState(null);return I.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 wr(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 pt(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=Ps(((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),m=s.useEditorStore(f=>f.isShowingVisual),u=n.sql;return{getUpdatedFrame:I.useCallback(()=>{var g;let f=u;u&&!u.includes("{{")&&(f=Sr(u),t(f));const j=(g=r==null?void 0:r.getState())==null?void 0:g.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:i,lastSelectedDatabase:c,lastSelectedTable:l,connectionId:d,sql:f,customCfg:m?n.customCfg:null,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},y=a.cards.map(C=>C.id===n.id?x:C);return{...a,cards:y,activeCardId:wr(y,a.activeCardId)}},[n,a,m,o,i,c,l,d,t,r,u])}}function Vs(){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:m,setIsDashboardPanelOpen:u}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=nr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),f=I.useCallback(async x=>{try{r(x);const{data:y,fromCache:g}=await pt((t==null?void 0:t.accessToken)||"",x.id,a);return Dr(y,o,i,c,l),{success:!0,fromCache:g}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,i,c,l]),j=I.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:g}=await pt((t==null?void 0:t.accessToken)||"",x.id,a),C=y.frameObject;if(!C)return{success:!1,error:"Visual has no frame data"};const k={...C,id:s.v4()};return m(h,k,"end"),c(!0),d(k.id),u(!1),{success:!0,fromCache:g}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,m,c,d,u]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:f,handleAddLibraryVisual:j,getUpdatedFrame:kr().getUpdatedFrame,refetch:p.refetch}}function Tr(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),[o,i]=I.useState(""),[c,l]=I.useState(""),[d,m]=I.useState(!1),[u,h]=I.useState(null),[p,f]=I.useState(!1),[j,x]=I.useState(null),[y,g]=I.useState(null),{setIsDashboardEditing:C,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:T}=Vs(),{resources:w,isLoading:v,isError:D,createResource:b,updateResource:A,deleteResource:S,duplicateResource:O,shareResource:M,isCreating:E,isDeleting:N,removeResourceShares:L,isSharing:B,isRemovingShares:P,isUpdatingShares:V}=rr(()=>{f(!1),x(null)},()=>{r(!1),i(""),l("")}),{handleShareSubmit:q,handleRemoveAccess:X}=Cr((u==null?void 0:u.id)||null,M,L);be();const K=w.filter(z=>{var J,ie;return((J=z==null?void 0:z.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=z==null?void 0:z.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),$=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),F=()=>{o.trim()&&b({title:o,description:c,isPrivate:!1})},U=z=>{x(z),f(!0)},_=()=>{j&&S(j.id)},{startUpdating:Y,stopUpdating:Q,isUpdating:G}=Vt(),Z=(z,J)=>{const ie=J.title!==void 0?"title":"description";Y(z,ie),A({resourceId:z,data:J},{onSuccess:()=>{Q(z,ie)},onError:()=>{Q(z,ie)}})},te=z=>{g(z),O(z,{onSettled:()=>g(null)})},ae=z=>{R(z)},se=z=>{T(z)},oe=z=>{const J=w.find(ie=>ie.id===z);J&&A({resourceId:z,data:{isPrivate:!J.isPrivate}})},H=z=>{h(z),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ke({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),v?e.jsx(zt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:z=>l(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:F,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),i(""),l("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:E,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),E?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:z=>a(z.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(us,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):K.map(z=>e.jsx(ir,{visual:z,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:U,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:H,isDeleting:N,isDuplicating:y===z.id,isTitleUpdating:G(z.id,"title"),isDescriptionUpdating:G(z.id,"description"),formatDate:$},z.id))})}),d&&u&&e.jsx(Xt,{resource:u,resourceType:ee.VISUAL,onShare:q,isSharing:B,isRemoving:P,isUpdating:V,onClose:()=>{m(!1),h(null)},onRemoveAccess:X}),e.jsx(s.AlertDialog,{open:p,onOpenChange:z=>{!z&&N||(f(z),z||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:N,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),_()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:N,children:N?"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:m,formatDate:u,onDashboardItemClick:h}){var w;const{selectDashboard:p}=s.useManagementActions(),f=s.useIsDashboardSelected(t.id),[j,x]=I.useState(!1),[y,g]=I.useState(!1),C=s.useDashboardStore(v=>v.actions.setIsDashboardPanelOpen);I.useEffect(()=>{n?(x(!0),g(!0)):y&&(x(!1),g(!1))},[n,y]);const k=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(It,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(De,{className:"h-3.5 w-3.5 text-slate-500"}),R=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),T=()=>{p(t),i(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",f&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:T,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:R()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:v=>c==null?void 0:c(t.id,{title:v}),isEditable:t.permissions.canEdit&&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:k()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:v=>c==null?void 0:c(t.id,{description:v}),isEditable:t.permissions.canEdit&&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:j,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:v=>v.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),d(t.id)},disabled: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:v=>{v.stopPropagation(),m(t)},children:[e.jsx(ve,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),l(t),C(!1)},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(De,{className:"h-3 w-3"}),e.jsx("span",{children:((w=t.ownership.createdBy)==null?void 0:w.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})})})]})]},t.id)}function 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 Mr(t){const[a,n]=I.useState(""),[r,o]=I.useState(!1),[i,c]=I.useState(""),[l,d]=I.useState(""),[m,u]=I.useState(!1),[h,p]=I.useState(null),[f,j]=I.useState(!1),[x,y]=I.useState(null),[g,C]=I.useState(null),k=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:T,isLoading:w,isError:v,createResource:D,updateResource:b,deleteResource:A,duplicateResource:S,isCreating:O,isDeleting:M,isSharing:E,isRemovingShares:N,isUpdatingShares:L,shareResource:B,removeResourceShares:P}=ar(()=>{j(!1),y(null),k&&R(k)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:q}=Nr((h==null?void 0:h.id)||null,B,P),{currentUser:X}=be(),K=T.filter(H=>{var z,J;return((z=H==null?void 0:H.title)==null?void 0:z.toLowerCase().includes(a.toLowerCase()))||((J=H==null?void 0:H.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),$=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),F=()=>{i.trim()&&D({title:i,description:l,isPrivate:!1})},U=H=>{var z;(z=t.onLoadDashboard)==null||z.call(t,H)},_=H=>{y(H),j(!0)},Y=()=>{x&&A(x.id)},Q=H=>{C(H),S(H,{onSettled:()=>C(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=Vt(),ae=(H,z)=>{const J=z.title!==void 0?"title":"description";G(H,J),b({resourceId:H,data:z},{onSuccess:()=>{Z(H,J)},onError:()=>{Z(H,J)}})},se=H=>{const z=T.find(J=>J.id===H);z&&b({resourceId:H,data:{isPrivate:!z.isPrivate}})},oe=H=>{p(H),X==null||X.type,u(!0)};return ke({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),w?e.jsx(zt,{}):v?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:H=>c(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:l,onChange:H=>d(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:F,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:H=>n(H.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(la,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):K.map(H=>e.jsx(Er,{dashboard:H,isDeleting:M,isDuplicating:g===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:U,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:_,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:$,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),m&&h&&e.jsx(Xt,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:E,isRemoving:N,isUpdating:L,onClose:()=>{u(!1),p(null)},onRemoveAccess:q}),e.jsx(s.AlertDialog,{open:f,onOpenChange:H=>{!H&&M||(j(H),H||y(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),Y()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function sn({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}=be(),l=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),u=Gt(a,{enabled:t}),h=f=>{},p=f=>{console.log("Editing dashboard:",f)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:u,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",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:m,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Mr,{onLoadDashboard:h,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Tr,{})})]})})]})})}function Ar(){var $;const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(F=>F.theme);const n=s.useDashboardStore(F=>F.lenses),r=s.useDashboardStore(F=>F.selectedLensId),o=n==null?void 0:n.find(F=>F.id===r),i=s.useDashboardStore(F=>F.dashboard);s.useDashboardStore(F=>F.selectedSheetId);const c=s.useDashboardStore(F=>F.isDashboardEditing),l=s.useEditorStore(F=>F.card),d=s.useEditorStore(F=>F.selectedConnectionId),[m,u]=I.useState(!1),h=s.useDashboardStore(F=>F.isDashboardPanelOpen),p=s.useDashboardStore(F=>F.actions.setIsDashboardPanelOpen),f=s.useDashboardStore(F=>F.filterValues),j=s.useDashboardStore(F=>F.isVisualEditing),x=s.useManagementStore(F=>F.selectedDashboard),y=($=x==null?void 0:x.permissions)==null?void 0:$.canEdit,g=s.useDashboardStore(F=>F.showFilters);s.useDashboardStore(F=>F.showDashboardJSON);const C=s.useDashboardStore(F=>F.onSaveFunction),k=s.useDashboardStore(F=>F.actions.setShowFilters),{addFrame:R,setSelectedFrameId:T}=s.useDashboardStore(F=>F.actions),{getSelectedSheet:w,setIsDashboardEditing:v,setShowDashboardJSON:D}=s.useDashboardStore(F=>F.actions),b=w(),{tenantId:A,endUserId:S}=I.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),O=I.useMemo(()=>A||S,[A,S]);function M(){var Y,Q;const F=l.dataSource;if(F)return F;const U=(Q=(Y=i.aiContext)==null?void 0:Y.selectedEntities)==null?void 0:Q[0],_=U==null?void 0:U.type;if(U)return{connectionId:U.connectionId,connectionType:U.connectionType,type:_,selectedEntities:[U]}}const E=()=>{if(!c||!b)return;const U={dataSource:M(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},_={id:s.v4(),cards:[U],activeCardId:U.id};R(b.id,_),T(_.id)},N=()=>{v(!0)},[L,B]=I.useState(!1),P=Pt(ee.DASHBOARD);async function V(){const F=ns(i);B(!0);const U={template:F};P.mutate({resourceId:F.id,data:U},{onSuccess:()=>{B(!1),s.ue.success("Dashboard saved!")},onError:()=>{B(!1),s.ue.error("Failed to save dashboard")}})}async function q(){if(u(!0),!r||!o)return;const F=ns(i),U=JSON.stringify(F),_={...o,template:U,filterValues:f};await Ds(_,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),C==null||C(F),u(!1)}if(j)return null;const X=(o==null?void 0:o.name)||i.title,K=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[K&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(ma,{className:"h-4 w-4"})}),!j&&e.jsx(s.Label,{children:X})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!j&&e.jsx(Ba,{}),!j&&e.jsx(Bt,{}),c&&!j&&O&&e.jsx(Ra,{}),!j&&O&&e.jsx(Fa,{}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:E,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!j&&!c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:N,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),c&&!j&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",onClick:()=>{v(!1),D(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),c&&!j&&O&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:q,size:"sm",children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),c&&!j&&O&&y&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:L,onClick:V,size:"sm",children:[L?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ws,{className:"mr-2 h-4 w-4"}),L?"Saving...":"Save"]}),!g&&!j&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>k(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!j&&c&&!1,!j&&!1,!j&&e.jsx(sn,{isOpen:h,onClose:()=>p(!1)})]})]})}function Lr({name:t,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:l,icon:d,showNone:m=!1}){const u=ue.useRef(null),[h,p]=ue.useState(!1),[f,j]=ue.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{u.current&&j(u.current.offsetWidth)},[]);function y(){var C;return o?"Loading...":i?"Error":n?(C=a==null?void 0:a.find(k=>k.id===n))==null?void 0:C.name:`Select ${t}`}function g(C,k){r(k),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",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:y()})]}),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(Mt,{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(C=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:k=>g(k,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function Pe({title:t,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:l=!1,className:d,disabled:m=!1,type:u="combobox"}){const h=r?"Loading...":o?"Error":n;function p(){if(t==="Connection")return e.jsx(Ca,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ba,{className:"size-4"});if(t==="Table")return e.jsx(Ve,{className:"size-4"});if(t==="Model")return e.jsx(Qn,{className:"size-4"})}function f(){return e.jsxs(s.Select,{disabled:m,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":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(Mt,{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,y)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},y))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Lr,{icon:p(),items:a,value:h,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:u==="select"?f():j()})})}function Or({column:t}){const[a,n]=I.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:m}=s.useEditorAside(),u=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function f(x,y){var R;const g=s.createSqlGenConfig(x,l,y),C=(R=d==null?void 0:d.find(T=>T.id===c))==null?void 0:R.name;u(g);const k=s.getSql(g,s.fmt(o||""),s.fmt(r),C||"",m,i||"");k&&(h(k),p(!0)),n(!1)}function j(){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:j()})]})}function _s({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(Ye,{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(ts,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function fs({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(_s,{column:t}),e.jsx("span",{children:t.column_name})]})}function Rr({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 Fr({onClick:t,column:a}){const n=s.useDndStore(u=>u.activeId),r=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.metricColumns}),i=s.useEditorStore(u=>{var h;return(h=u.card.queryConfig)==null?void 0:h.filterColumns});function c(u){return l(u)||d(u)||m(u)}function l(u){return r==null?void 0:r.some(h=>h.name===u.column_name)}function d(u){return o==null?void 0:o.some(h=>h.name===u.column_name)}function m(u){return i==null?void 0:i.some(h=>h.name===u.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(fs,{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(fs,{column:a})}),e.jsx(Rr,{id:a.column_name,type:"column",children:e.jsx(fs,{column:a})})]})}const gs={id:"__placeholder__",role:"groupby",type:"string"},js={id:"__placeholder__",role:"groupby",type:"string"},ys={id:"__placeholder__",role:"metric",type:"number"},vs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},tn={id:"__placeholder__"},Ie="droppable-group-by",Me="droppable-metrics",Ae="droppable-pivot-by",rs="sortable-group-by",ks="sortable-metrics",os="sortable-pivot-by",Ts="droppable-filters",Es="sortable-filters",Us="sortable-order-by";function Br(){const t=s.useDndStore(E=>E.insertIndex),a=s.useEditorStore(E=>{var N;return((N=E.card.queryConfig)==null?void 0:N.groupByColumns)||[]}),n=s.useEditorStore(E=>{var N;return((N=E.card.queryConfig)==null?void 0:N.metricColumns)||[]}),r=s.useEditorStore(E=>{var N;return((N=E.card.queryConfig)==null?void 0:N.filterColumns)||[]}),o=s.useEditorStore(E=>{var N;return((N=E.card.queryConfig)==null?void 0:N.orderBy)||[]}),i=s.useEditorStore(E=>{var N;return((N=E.card.queryConfig)==null?void 0:N.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:l,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:u,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:f,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:y}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:C}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=E=>{var B;const{active:N,over:L}=E;if(((B=N.data.current)==null?void 0:B.type)==="column"&&L){const P=L.id,V=g.find($=>$.column_name===N.id);if(!V)return;const q=s.isNumberDataType(V.data_type),X=s.isTextDataType(V.data_type),K=s.isDateDataType(V.data_type);if(X||K){if(a.some(F=>F.id===P)){const F=a.findIndex(_=>_.id===P);c(F);const U=a.filter(_=>_.id!==gs.id);U.splice(F,0,gs),d(U)}else if(L.id===Ie){c(a.length);const F=[...a,gs];d(F),m(n),u(r)}}if(X||K){if(i.some(F=>F.id===P)){const F=i.findIndex(_=>_.id===P);c(F);const U=i.filter(_=>_.id!==js.id);U.splice(F,0,js),h(U)}else if(L.id===Ae){c(i.length);const F=[...i,js];h(F),d(a),m(n),u(r)}}if(q||X){if(n.some(F=>F.id===P)){console.log("isOverMetricSortable",P);const F=n.findIndex(_=>_.id===P);c(F);const U=n.filter(_=>_.id!==ys.id);U.splice(F,0,ys),m(U)}else if(L.id===Me){c(n.length);const F=[...n,ys];m(F),u(r),d(a),h(i)}}if(w(V)){if(r.some(F=>F.id===P)){const F=r.findIndex(_=>_.id===P);c(F);const U=r.filter(_=>_.id!==vs.id);U.splice(F,0,vs),u(U)}else if(L.id===Ts){c(r.length);const F=[...r,vs];u(F),m(n),d(a),h(i)}}}else d(a),m(n),u(r),h(i)};function T(E){l(E.active.id),c(null),d(a),m(n),u(r),h(i)}function w(E){return!r.some(N=>N.name===E.column_name)}function v(E,N="SUM"){const{column_name:L,data_type:B}=E,P=[...n],V=t!==null?t:n.length,q={...E,id:fe(L),name:L,label:Ke(L,N),type:B,role:"metric",aggregate:N};P.splice(V,0,q),f(P)}function D(E){const N=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const L=[...i],B=t!==null?t:i.length;let P;N?P={...E,id:fe(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:P={...E,id:fe(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:_e(E.column_name,"month"),granularity:"month"},L.splice(B,0,P),y(L)}function b(E){const N=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const L=[...a],B=t!==null?t:a.length;let P;N?P={...E,id:fe(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:P={...E,id:fe(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:_e(E.column_name,"month"),granularity:"month"},L.splice(B,0,P),p(L)}function A(E){const N=[...r],L=t!==null?t:r.length,B={...E,id:fe(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,C,s.fmt(E.column_name)),role:"filter"};N.splice(L,0,B),j(N)}function S(E){var P,V,q,X,K,$,F,U;const{active:N,over:L}=E,B=N.data.current;if((B==null?void 0:B.type)==="column"&&L){const _=g.find(Z=>Z.column_name===N.id);if(!_)return;const Y=s.isNumberDataType(_.data_type),Q=s.isTextDataType(_.data_type),G=s.isDateDataType(_.data_type);(Q||G)&&(L.id===Ie||((P=L.data.current)==null?void 0:P.type)===rs)&&b(_),(Q||G)&&(L.id===Ae||((V=L.data.current)==null?void 0:V.type)===os)?D(_):(Y||Q)&&(L.id===Me||((q=L.data.current)==null?void 0:q.type)===ks)?(Y&&v(_),Q&&v(_,"COUNT")):w(_)&&(L.id===Ts||((X=L.data.current)==null?void 0:X.type)===Es)&&A(_)}if(L&&((K=L.data.current)==null?void 0:K.type)===rs&&a.some(_=>_.id===N.id)){const _=a.findIndex(Q=>Q.id===N.id),Y=a.findIndex(Q=>Q.id===L.id);if(_!==-1&&Y!==-1&&_!==Y){const Q=[...a],[G]=Q.splice(_,1);Q.splice(Y,0,G),p(Q)}}if(L&&(($=L.data.current)==null?void 0:$.type)===os&&i.some(_=>_.id===N.id)){const _=i.findIndex(Q=>Q.id===N.id),Y=i.findIndex(Q=>Q.id===L.id);if(_!==-1&&Y!==-1&&_!==Y){const Q=[...i],[G]=Q.splice(_,1);Q.splice(Y,0,G),y(Q)}}if(L&&((F=L.data.current)==null?void 0:F.type)===ks&&n.some(_=>_.id===N.id)){const _=n.findIndex(Q=>Q.id===N.id),Y=n.findIndex(Q=>Q.id===L.id);if(_!==-1&&Y!==-1&&_!==Y){const Q=[...n],[G]=Q.splice(_,1);Q.splice(Y,0,G),f(Q)}}if(L&&((U=L.data.current)==null?void 0:U.type)===Es&&r.some(_=>_.id===N.id)){const _=r.findIndex(Q=>Q.id===N.id),Y=r.findIndex(Q=>Q.id===L.id);if(_!==-1&&Y!==-1&&_!==Y){const Q=[...r],[G]=Q.splice(_,1);Q.splice(Y,0,G),j(Q)}}O(E),l(null),c(null),d(a),m(n),u(r),h(i)}function O(E){const{active:N,over:L}=E,B=N.data.current;if((B==null?void 0:B.type)===Us&&L){const P=o.findIndex(q=>$e(q.columnId)===N.id),V=o.findIndex(q=>$e(q.columnId)===L.id);if(P!==-1&&V!==-1&&P!==V){const q=[...o],[X]=q.splice(P,1);q.splice(V,0,X),x(q)}}}function M(){l(null),c(null),d(a),m(n),u(r)}return{handleDragOver:R,handleDragEnd:S,handleDragStart:T,handleDragCancel:M,sensors:k}}function fe(t){return`${t}-${s.v4()}`}function Ke(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 $e(t){return`${Us}-${t}`}function _e(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 zr({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(N=>N.sqlGen),i=s.useEditorStore(N=>N.isDevMode),c=s.useEditorStore(N=>N.selectedConnectionId),l=s.useEditorStore(N=>{var L,B;return(B=(L=N.card)==null?void 0:L.queryConfig)==null?void 0:B.metricColumns});s.useEditorStore(N=>{var L,B;return(B=(L=N.card)==null?void 0:L.queryConfig)==null?void 0:B.groupByColumns});const d=s.useEditorStore(N=>N.selectedDatabaseName),m=s.useEditorStore(N=>N.selectedSchemaName),u=s.useEditorStore(N=>N.selectedTableName),h=s.useEditorStore(N=>N.selectedDatamodelId),p=s.useDashboardStore(N=>N.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:y,setCardSql:g,setRunSql:C,setSqlGen:k,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:T,modelItems:w,selectedDatamodelName:v}=s.useEditorAside();function D(N){var L;if(i){const B=s.createSqlGenConfig(N,o);k(B);const P=(L=w==null?void 0:w.find(q=>q.id===h))==null?void 0:L.name,V=s.getSql(B,s.fmt(t),s.fmt(a),P||"",T,d||"");V&&(g(V),C(!0))}if(!i){if(s.isTextDataType(N.data_type))if(l&&l.length>0){const B={...N,role:"groupby",id:fe(N.column_name),name:N.column_name,type:N.data_type};y(B)}else{const B={...N,role:"metric",id:fe(N.column_name),name:N.column_name,label:Ke(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};x(B)}if(s.isDateDataType(N.data_type)){const B={...N,role:"groupby",id:fe(N.column_name),name:N.column_name,type:N.data_type,label:_e(N.column_name,"month"),granularity:"month"};y(B)}if(s.isNumberDataType(N.data_type)){const B={...N,role:"metric",id:fe(N.column_name),name:N.column_name,label:Ke(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};x(B)}}}function b(N){N===!0&&(u||v)&&c?(f({connectionId:c,connectionType:T==="S3"||T==="API"?"DuckDb":T||"",databaseName:d||"",schemaName:m||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:c||"",connectionType:T||"",tableName:u||"",datamodelName:s.resolveDatamodelName(v),datamodelId:h||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function A(){const N=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:v,connectionType:T,databaseName:d||""});R(!1);const L=T==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;g(L),C(!0)}function S(){const N=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:v,connectionType:T,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${N}`),C(!0)}function O(){return(p==null?void 0:p.find(N=>N.connectionId===c&&(N.tableName===u||N.datamodelName===v)))!==void 0}function M(N){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(N),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_s,{column:N}),e.jsx("span",{children:N.column_name})]}),e.jsx("div",{onClick:L=>L.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(N.data_type)&&e.jsx(Or,{column:N})})]}):e.jsx(Fr,{onClick:D,column:N})}function E(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:b,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:A,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(ga,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((N,L)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},L))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:E()}),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(N=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:M(N)},N.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function nn({ColumnsComponent:t,type:a}){var Te;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),m=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:u,setIsDevMode:h,setCardSql:p}=s.useEditorActions(),{connectionItems:f,modelItems:j,schemaItems:x,databaseItems:y,tableItems:g,columns:C,isConnectionsLoading:k,isModelsLoading:R,isConnectionsError:T,isModelsError:w,isDatabasesLoadingOrFetching:v,isDatabaseError:D,isSchemaLoadingOrFetching:b,isSchemaError:A,isColumnsError:S,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:M,isTableError:E,connectionType:N,isNonDbConnection:L,refetchDatabases:B,refetchModels:P,refetchSchemas:V,refetchTables:q,refetchColumns:X,refetchConnections:K,handleConnectionChange:$,handleDatabaseChange:F,handleSchemaChange:U,handleDatamodelChange:_,handleTableChange:Y,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,C):e.jsx(zr,{schemaName:G,tableName:Q,columns:C,status:O?"Loading...":S?"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(""),h(ne)}function H(){if(!r||N==="S3"||N==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:B,showNone:!0,onChange:F,isError:D,isLoading:v,items:y,value:c||"",title:"Database",type:"combobox"})}function z(){if(r&&!L&&(!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||N==="S3"||N==="API")return null;if(!c||c==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:_,isError:w,isLoading:R,items:j,value:i||"",title:"Model",type:"combobox"})}function ie(){return!r||N==="S3"||N==="API"||!c||c==="none"?null:e.jsx(Pe,{refetch:V,onChange:U,isError:A,isLoading:b,items:x,value:l||"",title:"Schema",type:"combobox"})}function Ne(){function ne(){let le=!1;return N==="API"?(le=!1,le):((N==="S3"||r&&c&&c!=="none"&&l)&&(le=!0),le)}return ne()?e.jsx(Pe,{refetch:q,onChange:Y,isError:E,items:g,isLoading:M,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(Pe,{refetch:K,items:f,title:"Connection",value:r||"",onChange:$,isLoading:k,isError:T,type:"combobox",connectionTooltip:((Te=f==null?void 0:f.find(ne=>ne.id===r))==null?void 0:Te.type)||""}),H(),z(),J(),ie(),Ne()]}),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:m,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(ya,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function an({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=I.useState(!1),c=I.useRef(null),l=I.useRef(!1);function d(){t&&!l.current&&navigator.clipboard.writeText(t)}function m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function u(){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 h(){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:m,onMouseUp:u,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function rn({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(an,{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(aa,{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(ua,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function on({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(Tt,{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(rn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var ln={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ft=I.createContext&&I.createContext(ln),Pr=["attr","size","title"];function Vr(t,a){if(t==null)return{};var n=_r(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 _r(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 is(){return is=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},is.apply(this,arguments)}function gt(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 ls(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?gt(Object(n),!0).forEach(function(r){Ur(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ur(t,a,n){return a=qr(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function qr(t){var a=$r(t,"string");return typeof a=="symbol"?a:a+""}function $r(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 cn(t){return t&&t.map((a,n)=>I.createElement(a.tag,ls({key:n},a.attr),cn(a.child)))}function Oe(t){return a=>I.createElement(Yr,is({attr:ls({},t.attr)},a),cn(t.child))}function Yr(t){var a=n=>{var{attr:r,size:o,title:i}=t,c=Vr(t,Pr),l=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),I.createElement("svg",is({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:ls(ls({color:t.color||n.color},n.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),i&&I.createElement("title",null,i),t.children)};return ft!==void 0?I.createElement(ft.Consumer,null,n=>a(n)):a(ln)}function Gr(t){return Oe({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 dn(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:m}=s.useEditorActions(),u=I.useRef(),h=I.useRef({}),p=r.cards.find(x=>x.id===i),f=I.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]);I.useEffect(()=>{if(i&&o.id&&o.id!==i){if(u.current&&c){const x=u.current.getModel();x&&(h.current[o.id]=x);let y=h.current[i];if(!y){const g=f();y=c.editor.createModel(g,t),h.current[i]=y}u.current.setModel(y)}d(i,o),m(!0)}},[i,o,d,c,m,t,f]),I.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=n==="system"?x:n;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),I.useEffect(()=>{const x=u.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return l(),!1})},[c,l,o]);function j(x,y){if(u.current=x,!h.current[o.id]){const g=x.getModel(),C=f();h.current[o.id]=g||(y==null?void 0:y.editor.createModel(C,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:j}}function Hr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=dn("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}=dn("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 Kr({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function qs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(l=>l.frame);const n=s.useEditorStore(l=>l.card);Ps(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(l=>l.selectedSchemaName),s.useEditorStore(l=>l.selectedDatamodelId),s.useEditorStore(l=>l.selectedDatabaseName),s.useEditorStore(l=>l.selectedTableName),s.useEditorStore(l=>l.selectedConnectionId),s.useEditorStore(l=>l.isShowingVisual),n.sql;const r=s.useEditorStore(l=>l.onSave),{getUpdatedFrame:o}=Vs();function i(){const l=o();r==null||r(l)}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Wr(){const t=s.useQueryClient(),[a,n]=I.useState(!1),r=s.useDashboardStore(m=>m.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:i}=Vs(),c=s.useSelectedVisual(),l=or(),d=()=>{const m=i();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),l.mutate({visualId:c.id,data:{frameObject:m}},{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(ws,{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:m}=r;d&&m&&n.setQueryData(d,m)}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 ms(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),o=s.useEditorStore(y=>y.card),{queryKey:i}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:l,setCardPython:d,setCardCustomCfg:m,setCardPreferences:u,updateDataSource:h,clearQueryConfig:p,setCardConfig:f,setCardType:j}=s.useEditorActions();function x(){const y=a.getQueryData(i);r!=null&&r.queryData||t({queryKey:i,queryData:y}),a.setQueryData(i,null),a.removeQueries({queryKey:i,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),l({}),p(),f(void 0),d(""),m(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Jr(){const t=s.useQueryClient(),[a,n]=I.useState(!1),[r,o]=I.useState(!1);s.useEditorStore(q=>q.frame);const i=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.isShowingVisual),s.useEditorStore(q=>q.selectedConnectionId),s.useEditorStore(q=>q.tempQueryData),s.useEditorStore(q=>q.selectedDatabaseName),s.useEditorStore(q=>q.selectedDatamodelId),s.useEditorStore(q=>q.selectedSchemaName);const c=s.useEditorStore(q=>q.showAIDialog);s.useEditorStore(q=>q.selectedTableName);const l=s.useEditorStore(q=>{var X;return(X=q==null?void 0:q.card)==null?void 0:X.sql}),d=s.useEditorStore(q=>{var X;return(X=q==null?void 0:q.card)==null?void 0:X.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:h,setCardSql:p,setTempQueryData:f,setPythonStdOut:j,setCardPreferences:x,setCardType:y,setCardPython:g,runAssistant:C,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(q=>q.onSave),s.useEditorStore(q=>q.onClose),s.useEditorStore(q=>q.actions.setSqlGen);const R=s.useEditorStore(q=>q.runSql),T=s.useEditorStore(q=>q.actions.setRunSql),w=s.useEditorStore(q=>q.actions.setIsSqlRunning),{data:v,isLoading:D,isFetching:b,isSuccess:A,isError:S,error:O,queryKey:M,refetch:E,errorMessage:N}=s.useDashboardCardQuery(i);I.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:q}=s.getKeys(v.records);h(q)}},[v,h,j]),I.useEffect(()=>{(D||b)&&w(!0),(S||A)&&w(!1),S&&(h([]),j(""))},[D,b,v,j,S,A,w,h,O]),I.useEffect(()=>{R&&(t.getQueryData(M)||E(),T(!1))},[R,E,T,M,t]);async function L(){const q=`Can you help me debug this query in the current table scope?
|
|
417
417
|
|
|
418
418
|
Error:
|
|
419
419
|
|
|
@@ -425,11 +425,11 @@
|
|
|
425
425
|
|
|
426
426
|
${d?`Python:
|
|
427
427
|
${d}`:""}
|
|
428
|
-
`;C(U)}function B(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Kr,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.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(Hr,{})}),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 V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:D||b,onClick:()=>{T()},className:"h-8 shrink-0",size:"sm",children:[D||b?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(on,{sql:y==null?void 0:y.sql,error:N,onDebugWithAssistant:L}),e.jsx(ms,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:U=>n(U),className:"",size:"sm",children:e.jsx(Gr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{}),e.jsx(qs,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),B()]}),V()]})}function Xr({data:t}){var c;const[a,n]=I.useState([]),o=Object.keys(t[0]).map(l=>({accessorKey:l,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[l,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),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 C,k,O,E,w,y,D,b,A,S,R;const[a,n]=I.useState(!1),[r,o]=I.useState([]),{authToken:i}=s.useSemaphorContext(),c=s.getTokenParams(i==null?void 0:i.accessToken),l=s.useDashboardStore(M=>M.themeStyle),d={colors:((k=(C=l==null?void 0:l.chart)==null?void 0:C.dataset)==null?void 0:k.backgroundColor)||[]};(O=t.customCardPreferences)!=null&&O.inputData;const{getCard:m}=s.useCustomVisual(((E=t.customCardPreferences)==null?void 0:E.url)||""),u=((w=t.customCardPreferences)==null?void 0:w.visualType)||"single",h=s.useEditorStore(M=>M.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),g=I.useCallback((M,T)=>{o(N=>({...N,[M]:T}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const x=m((D=t.customCardPreferences)==null?void 0:D.componentName);function v(M){n(M)}const j=Object.keys(((b=t.customCardPreferences)==null?void 0:b.dataInputCardIds)||{}).map(M=>{var L,B,P;const T=(B=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:B[M].cardId,N=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===T);return N||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(I.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&u==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(A=t.customCardPreferences)==null?void 0:A.settings,onDataChange:g,data:(f==null?void 0:f.records)||[]}),x&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(M=>{var L,B,P;const T=(B=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:B[M].cardId,N=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===T);if(N)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:M,card:N},N.id+M)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(M=>{var T;return(T=M==null?void 0:M.customCardPreferences)==null?void 0:T.settings}),data:j.map(M=>M!=null&&M.id?r==null?void 0:r[M.id]:[])})})]})]},(R=t.customCardPreferences)==null?void 0:R.componentName)})}function un({className:t,...a}){var D;const n=s.useEditorStore(b=>b.card),r=s.isExplorerCard(n),o=((D=n.customCardPreferences)==null?void 0:D.showCardHeader)??!0,i=s.useEditorStore(b=>b.frame),c=s.useDashboardStore(b=>b.dashboard.filters),l=s.useEditorStore(b=>b.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(b=>b.id===i.filterId),{data:u,isLoading:h,isFetching:p,errorMessage:f,pagination:g,refetch:x}=s.useDashboardCardQuery(n),{setCard:v,updateCardInFrame:j}=s.useEditorActions(),{data:C}=s.useTopoJson(n),k=I.useMemo(()=>n.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:n,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[n,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),O=(b,A)=>{var R,M;const S={...n,paginationConfig:{page:b+1,pageSize:A}};v(S),j(S),n.sql&&((M=(R=n.preferences)==null?void 0:R.tablePrefs)!=null&&M.enableDevModePagination)&&l(!0)},E=I.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:C}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,C]);function w(b){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Zr,{card:b})})}function y(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!p)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return w(n);if(!["table","pivotTable","custom"].includes(n.type)&&E)return e.jsx(e.Fragment,{children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:E})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(u==null?void 0:u.records)||[],paginationMetadata:g,onPaginationChange:O,isLoading:h||p})});if(n.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:k.data,options:k.options,onAggregationChange:b=>{const A=s.handleAggregationChange(b,n.config),S={...n,config:A};v(S),j(S)},onAggregationLabelChange:b=>{const A=s.handleAggregationLabelChange(b,n.config),S={...n,config:A};v(S),j(S)}})})}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:b=>v({...n,title:b}),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:b=>v({...n,description:b}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:b=>d({...m,title:b}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:y()})]})}const bs=({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(bs,{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(bs,{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(bs,{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]=I.useState(!1),[n,r]=I.useState(""),[o,i]=I.useState(""),[c,l]=I.useState(""),[d,m]=I.useState(""),u=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:f}=s.useDashboardCardQuery(u),{data:g}=s.useTopoJson(u),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=E=>{var w,y;return JSON.stringify({...E,data:{...E.data,datasets:(y=(w=E.data)==null?void 0:w.datasets)==null?void 0:y.map(D=>({...D,data:[]}))}},null,2)},C=()=>{var w,y;if(!((w=f==null?void 0:f.records)!=null&&w.length))return;const E=s.createChartConfig({card:u,data:f.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:g});if(E){r(j(E)),l(((y=u.preferences)==null?void 0:y.customVisualCode)||"");const D=s.merge(E,h);i(j(D))}},k=()=>{try{if(c&&v(c),o){const E=JSON.parse(o),w=s.getObjectDiff(JSON.parse(n),E);x(w),m("")}}catch{m("Invalid JSON configuration")}},O=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:C,className:O?"":"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.FallbackVisual,children:e.jsx(un,{className:"w-1/2 rounded shadow-none"})}),e.jsx(so,{customCode:c,cardCustomCfgString:p,mergedConfig:o,onConfigChange:E=>i(E??""),onCodeChange:E=>l(E??"")})]}),e.jsx(to,{error:d,hasCardCustomConfig:!!h,onReset:()=>{i(n),x(null)},onApply:k,onClose:()=>a(!1)})]})]})}function hs(t){const[a,n]=I.useState(null);return a}function Ys(){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]=I.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=s.useEditorActions(),{data:l}=Ys();function d(m,u){r(null),o({}),i(m),u&&c({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()}return I.useEffect(()=>{(async()=>{var u;if(l){const p=(await Promise.all((u=l==null?void 0:l.plugins)==null?void 0:u.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((m,u)=>e.jsx(ro,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+u))})]})}const ro=({text:t,icon:a,onClick:n})=>{const r=hs(),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 Gs(t){return Re({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 Re({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 Hs(t){return Re({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 Re({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Ks(t){return Re({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 Ws(t){return Re({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 mn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function d(u,h){i(null),r({}),n(u),["custom","text","map"].includes(u)&&(o(!0),l(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(cs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(us,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,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:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Bs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(wt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Fs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ye,{className:s.cn("size-5",a)})})]})}function io({chartType:t,className:a,customIcon:n,componentName:r}){const o=hs();switch(t){case"bar":return e.jsx(cs,{className:a});case"line":return e.jsx(ds,{className:a});case"pie":return e.jsx(us,{className:a});case"radar":return e.jsx(Bs,{className:a});case"scatter":return e.jsx(Rs,{className:a});case"bubble":return e.jsx(Hs,{className:a});case"doughnut":return e.jsx(Os,{className:a});case"stackedBar":return e.jsx(As,{className:a});case"stackedLine":return e.jsx(Ks,{className:a});case"polarArea":return e.jsx(Gs,{className:a});case"funnel":return e.jsx(Qs,{className:a});case"tornado":case"pyramid":return e.jsx(zs,{className:a});case"range":return e.jsx(Ls,{className:a});case"kpi":return e.jsx(Ws,{className:a});case"text":return e.jsx(Qe,{className:a});case"map":return e.jsx(Fs,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ye,{className:a});default:return e.jsx(He,{className:a})}}function hn({variant:t="ghost"}){var i,c;const[a,n]=I.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(mn,{onChartTypeChange:()=>n(!1)}),e.jsx(ao,{onChartTypeChange:()=>n(!1)})]})]})}const We="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function jt(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 L,B,P,V,U,X;const[t,a]=I.useState(!1),n=s.useEditorStore(K=>{var F;return(F=K.card)==null?void 0:F.preferences}),r=s.useEditorStore(K=>{var F;return(F=K.card)==null?void 0:F.type}),o=s.getNumberAxis(n,{}),[i,c]=I.useState(jt(n,r)),[l,d]=I.useState(((P=(B=(L=n==null?void 0:n.chartOptions)==null?void 0:L.scales)==null?void 0:B[o])==null?void 0:P.min)||""),[m,u]=I.useState(((X=(U=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:U[o])==null?void 0:X.max)||""),[h,p]=I.useState(l||m?"custom":"auto"),[f,g]=I.useState(""),[x,v]=I.useState(0),[j,C]=I.useState(""),[k,O]=I.useState(""),[E,w]=I.useState(""),y=s.useEditorStore(K=>K.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),b=s.useEditorStore(K=>K.card),A=["pie","doughnut","polarArea","funnel"].includes(r);I.useEffect(()=>{var K,F,_,$,q,Y,Q,G,Z,te,ae,se,oe,H;c(jt(n,r)),d(((_=(F=(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales)==null?void 0:F[o])==null?void 0:_.min)===0?0:""),u(((Y=(q=($=n==null?void 0:n.chartOptions)==null?void 0:$.scales)==null?void 0:q[o])==null?void 0:Y.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),C(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),O(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),w(((H=n==null?void 0:n.numberAxisFormat)==null?void 0:H.locale)||"")},[t,n,o,r]);function S(K,F){return F===""||/^[0-9\b]+$/.test(F)?Number(F):Number(K)}function R(){const K=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(F=>F.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:k||"none",onValueChange:F=>O(F==="none"?"":F),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),K.map(F=>e.jsx(s.SelectItem,{value:F,children:F},F))]})})]}),e.jsxs(s.Select,{value:E,onValueChange:F=>w(F),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(F=>e.jsx(s.SelectItem,{value:F.locale,children:F.locale},F.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:F=>v(Number(F.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${We}`})]})]})}function M(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:A,value:i,onValueChange:K=>c(K),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),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:A,id:"scale-option",value:h,onValueChange:K=>p(K),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&i=="linear"&&T()]})}function T(){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:K=>d(F=>S(F,K.target.value)),className:`col-span-1 h-8 w-full ${We}`}),e.jsx(s.Input,{value:m,onChange:K=>u(F=>S(F,K.target.value)),id:"max",className:`col-span-1 h-8 w-full ${We}`})]}),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:K=>g(F=>S(F,K.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${We}`})]})]})}function N(){var $;let K={};h==="custom"&&(K={min:l,max:m,ticks:{stepSize:f}});const F={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...($=n==null?void 0:n.chartOptions)==null?void 0:$.scales,[o]:{type:i,...i==="linear"?K:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:k,locale:E}};console.log(F),y(F);const _={...b,preferences:F};D(_)}return e.jsxs(s.Popover,{onOpenChange:K=>a(K),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(ta,{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:[R(),M(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:N,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function co(){const t=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.position}),a=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.align}),n=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.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(ha,{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(qn,{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(Bn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Fn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(zn,{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(dt,{className:"size-4"}):e.jsx(ct,{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(dt,{className:"size-4"}):e.jsx(ct,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function xn(){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(da,{className:"size-4"}),r==="x"&&e.jsx(Xn,{className:"size-4"}),r==="y"&&e.jsx(Sa,{className:"size-4"}),r==="none"&&e.jsx(Ta,{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),[C]=j.splice(parseInt(v),1);j.splice(x,0,C),n({...t,cards:j})};function m(g){const x=t.cards.filter(C=>C.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function u(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function h(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(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"};u(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(na,{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:()=>m(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:h,children:e.jsx(ea,{className:"h-4 w-4"})})]})})}function pn(){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:m,isLoading:u,isFetching:h}=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(C=>C.id===a.id?a:C),activeCardId:x};o(v);const j=v.cards.find(C=>C.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:m==null?void 0:m.records,isPending:u||h})})}):a.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(un,{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 Je({children:t}){var O,E;s.useEditorStore(w=>w.frame);const a=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),o=s.useDashboardStore(w=>w.isVisualEditing),i=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:l,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:f,isFetching:g,errorMessage:x,refetch:v}=s.useDashboardCardQuery(a);function j(){const w=JSON.stringify(p==null?void 0:p.records,null,2),y=new Blob([w],{type:"application/json"}),D=URL.createObjectURL(y),b=document.createElement("a");b.href=D,b.download=`${a.title}.json`,b.click()}function C(){const y=[Object.keys(p==null?void 0:p.records.reduce((S,R)=>({...S,...R}),{})).join(","),...((p==null?void 0:p.records)||[]).map(S=>Object.values(S).join(","))].join(`
|
|
429
|
-
`),D=new Blob([y],{type:"text/csv"}),b=URL.createObjectURL(D),A=document.createElement("a");A.href=b,A.download=`${a.title}.csv`,A.click()}function k(){const w=`Can you get the documentation for ${a.type} chart?`;m(w)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(hn,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(Hn,{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:C,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:j,children:e.jsx(ra,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(xn,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((E=(O=a.preferences)==null?void 0:O.tablePrefs)==null?void 0:E.enableDevModePagination)??!1,onCheckedChange:w=>{var y;h({...a.preferences,tablePrefs:{...(y=a.preferences)==null?void 0:y.tablePrefs,enableDevModePagination:w}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xo,{})]}),r?e.jsx(pn,{}):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:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(Xr,{data:(p==null?void 0:p.records)||[]}),x&&e.jsx(an,{error:x})]})]})]}):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}=Ys(),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)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function u(j,C){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:C,hookRef:null}};c({...t,dataInputCardIds:O})}function h(j){var k,O;const C=(k=o==null?void 0:o.cards)==null?void 0:k.filter(E=>{var w;return((w=E==null?void 0:E.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(O=j==null?void 0:j.dataInputs)==null?void 0:O.map((E,w)=>{var y,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((D=(y=t==null?void 0:t.dataInputCardIds)==null?void 0:y[w])==null?void 0:D.cardId)||"",onValueChange:b=>u(w,b)})]},w+Math.random())})})}function p(j,C,k=[],O=""){var E,w;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[C])||O,onChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:y.target.value}})}},C):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:k,value:((w=t==null?void 0:t.settings)==null?void 0:w[C])||O,onValueChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:y}})}}):null:null}function f(j){const C=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([k,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),p(O.ui,k,O.options,O.defaultValue)]},k))})}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(Gn,{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(Zn,{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:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function Oe(){const[t,a]=I.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(m=>m.actions),i=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),I.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(m,u){var h,p;u?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):o({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(o({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(f=>f.columnIndex!==m)}),a(f=>{const g=[...f];return g[m]=!1,g}))}function l(m,u){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===m?{...f,expression:u.target.value}:f);o({...n,onClickFilter:h})}function d(m){var u,h,p,f;if(t!=null&&t[m]||(h=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(g=>g.columnIndex===m))!=null&&h.expression)return e.jsx(s.Input,{value:(f=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))==null?void 0:f.expression,onChange:g=>l(m,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((m,u)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===u)),onCheckedChange:f=>c(u,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===u))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const g=[...f];return g[u]=!f[u],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function fo({idx:t}){var l;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.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,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:u}]});else{const h={...i};h.datalabels=u;const p=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Lt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(xa,{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(fa,{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(pa,{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 Js({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 fn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data: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:gn(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,m)=>e.jsx(jn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function gn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function jn({col:t,idx:a,className:n,iconClassName:r,children:o}){const i=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,p;return(p=(h=u.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),l=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!l)d({...i,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...l};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?h: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(Js,{className:"max-w-[100px]",title:t,children:gn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(cs,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ds,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(kt,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fo,{idx:a})]})]})}function yn(){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:m,tableName:u,connectionType:h}=s.useEditorAside();function p(f,g="dashboard"){var y;const x=s.fmt(f.column_name),v=s.fmt(n||""),j=s.fmt(r||""),C=s.fmt(u);let k=s.getQualifiedTableName({schemaName:j,tableName:C,connectionType:h,databaseName:v}),O=`${k}.${x}`;const E=(y=m==null?void 0:m.find(D=>D.id===a))==null?void 0:y.name;a&&a!=="none"&&(O=`${s.DATAMODEL_NAMESPCACE}.${E}.${x}`,k=`${s.DATAMODEL_NAMESPCACE}.${E}`);const w=i==null?void 0:i.find(D=>D.column===O&&D.table===C&&(D.database===v||D.database===n));if(w)d(w.id),l(w.id);else{const D=s.v4();return u==="api"&&t?(c({location:g,id:D,column:O,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,k,x)}),D):(c({id:D,location:g,column:O,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,k,x)}),D)}}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}=yn();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 m=d===o?"":d;i(m),r(!1),m&&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(fn,{})})]}),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(Oe,{}),e.jsx(_e,{})]})]})]})})}function xs(){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 u;const d={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins,...d}}};r(m)}function i(){var l,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:m.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(xs,{})})]}),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(Oe,{}),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(xs,{}),e.jsx(Oe,{}),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 Ns({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"],Eo=ko.map(t=>({label:t,value:t}));function To(){var d,m,u,h,p,f,g,x,v,j,C,k,O,E,w,y,D,b;const t=s.useEditorStore(A=>A.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=I.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(A=>({label:A,value:A}))||[],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(Ns,{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(Ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:l,onValueChange:A=>{console.log("value",A),o({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.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:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:A}})}})]}),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:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Eo,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ns,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(E=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[0])||0,onChange:A=>{var S,R,M,T;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(A.target.value),((T=(M=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((b=(D=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:b[1])||0,onChange:A=>{var S,R,M,T;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((T=(M=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:T[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oe,{})]})}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 Xe({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(xs,{}),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(Oe,{}),e.jsx(_e,{})]})]})]})})}function Mo(){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(fn,{})]})]}),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(Oe,{}),e.jsx(_e,{})]})]})]})})}function Ao({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(Oe,{}),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 Fo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Mo,{});case"tornado":case"pyramid":return e.jsx(Xe,{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(Xe,{docContent:Ro,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Xe,{cardType:n});case"bubble":case"scatter":return e.jsx(vo,{cardType:n});case"table":return e.jsx(Ao,{cardType:n});case"text":return e.jsx(Xe,{docContent:Oo,cardType:n,suffix:"Visual"});case"map":return e.jsx(To,{});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 vn({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 Bo=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx($e,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ia,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(_n,{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 zo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Bo;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:Ke(t.name,o)};a(t.id,i)}return e.jsx(vn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Po=[{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 Vo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:Ve(t.name,r)};a(t.id,o)}return e.jsx(vn,{column:t,functions:Po,onFunctionChange:r=>n(r),label:"Granularity"})}function _o({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=I.useMemo(()=>{let l=[];(n===Te||n===Ie||n===Me)&&(l=r);const d=l==null?void 0:l.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),i=[{id:t.name,value:t.name}];function c(l){const d=r==null?void 0:r.find(m=>{var u;return m.column_name===((u=l[0])==null?void 0:u.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 bn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.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(jn,{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(xs,{})]})}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]=I.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:l,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:u,setNodeRef:h,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(w){const y=s.isNumberDataType(w.data_type),D=s.isTextDataType(w.data_type),b=s.isDateDataType(w.data_type),A=y?"number":D?"string":b?"date":"string";if(r===Te){if(D){const S={id:t.id,name:w.column_name,type:A,role:"groupby"};c(t.id,S)}if(b){const S={id:t.id,name:w.column_name,type:A,role:"groupby",label:Ve(w.column_name,"month"),granularity:"month"};c(t.id,S)}}if(r===Me){if(D){const S={id:t.id,name:w.column_name,type:A,role:"groupby"};d(t.id,S)}if(b){const S={id:t.id,name:w.column_name,type:A,label:Ve(w.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,S)}}if(r===Ie){const S={id:t.id,name:w.column_name,type:A,role:"metric",label:Ke(w.column_name,"SUM"),aggregate:y?"SUM":"COUNT"};l(t.id,S)}}function C(){if(r===Ie)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(bn,{column:t})})}function k(){const w=s.isDateDataType(t.type);if(r===Ie)return e.jsx(zo,{column:t});if((r===Te||r===Me)&&w)return e.jsx(Vo,{column:t})}function O(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Te||r===Me)&&v}),children:e.jsx(_o,{col:t,onChange:j,droppableId:r})})}function E(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(ka,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[E(),k(),O()]}),o&&C()]}),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 Cs({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}),m=s.useDndStore(j=>j.activeId),u=s.useEditorStore(j=>{var C;return(C=j.card)==null?void 0:C.type}),h=l||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,p=m?r:n,f=o===rs?"Rows":o===os?"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",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),u!=="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===tn.id?e.jsx(qo,{},j.id):e.jsx(Uo,{droppableId:t,type:o,column:j,onRemoveColumn:i},j.id))})]})})}function qo(){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 Nn({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}}),m=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:m,children:t})}function $o(){const t=s.useEditorStore(j=>{var C;return(C=j.card.queryConfig)==null?void 0:C.orderBy})||[],a=s.useEditorStore(j=>{var C;return(C=j.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=s.useEditorStore(j=>{var C;return(C=j.card.queryConfig)==null?void 0:C.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(Yn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Vn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Pn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(j=>!t.some(C=>C.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function p(j,C){const k=f(j);return k?k.role==="metric"?C==="asc"?m:u:C==="asc"?l:d:null}function f(j){return c.find(C=>C.id===j)}function g(j){const C=t.find(k=>k.columnId===j);if(C){const k={...C,direction:C.direction==="asc"?"desc":"asc"};i(k)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const C=t.find(k=>k.columnId===j);C&&o(C)}return e.jsx(s.SortableContext,{items:t.map(j=>qe(j.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var C,k;return e.jsx(Nn,{id:qe(j.columnId),type:Us,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Js,{className:"w-[175px] text-sm",children:((C=f(j.columnId))==null?void 0:C.label)||((k=f(j.columnId))==null?void 0:k.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)},qe(j.columnId))})]})})}function Yo(){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:m}=s.useEditorActions();function u(v){l(v)}function h(v){d(v)}function p(v){m(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(mn,{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(Cs,{onRemoveColumn:u,sortableType:rs,id:Te,label:f,columns:t,previewColumns:n}),e.jsx(Cs,{onRemoveColumn:p,sortableType:os,id:Me,label:x,columns:i,previewColumns:c}),e.jsx(Cs,{onRemoveColumn:h,sortableType:ks,id:Ie,label:g,columns:r,previewColumns:o}),e.jsx($o,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Xs({children:t,column:a,id:n,sortableType:r,className:o}){const[i,c]=I.useState(!1),{removeEditorFilter:l,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(h=>{var p,f;return(f=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(g=>g.filterColumnName===a.name)});function u(h){l(h)}return e.jsx(Nn,{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}),m&&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:()=>u(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 Go({column:t,sortableType:a}){const n=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var O,E;return(E=(O=k.card)==null?void 0:O.queryConfig)==null?void 0:E.filters}),o=s.useEditorStore(k=>{var O,E;return(E=(O=k.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:E.find(w=>w.name===t.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:l}=s.useEditorAside(),d=I.useMemo(()=>{var k;return(k=r==null?void 0:r.find(O=>O.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),m=I.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:i,dataType:t.type},{data:p,isLoading:f,isFetching:g,isError:x}=s.useFilterQuery(h),v=I.useMemo(()=>{var O;return h.column?(O=p==null?void 0:p.records)==null?void 0:O.map(E=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return E[w]===void 0&&(w=w.toLowerCase()),{id:E[w],value:E[w]}}):[]},[p,h.column]);function j(k){const O=k.map(E=>E.id);u(t.name,O)}function C(){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(Ho,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Xs,{className:"w-60",id:t.id,sortableType:a,column:t,children:C()})}function Ho({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]=I.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:m,isError:u,data:h}=s.useFilterQuery(l),p=h==null?void 0:h.records,{dateRange:f,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:v}=s.useEditorActions();function j(O){var w,y;const E={gte:(w=O==null?void 0:O.from)==null?void 0:w.toISOString(),lte:(y=O==null?void 0:O.to)==null?void 0:y.toISOString()};v(t.name,E)}function C(){v(t.name,null,!0),g(x)}function k(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:l.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:g,onApply:j,onClear:C}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Xs,{className:"w-72",id:t.id,sortableType:a,column:t,children:k()})}function Ko({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),m={},u=c||((x=(g=l==null?void 0:l.data)==null?void 0:g.current)==null?void 0:x.type)===o;function h(){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===tn.id?e.jsx(Xs,{id:v.id,sortableType:o,column:v,children:e.jsx(Wo,{})},v.id):j?e.jsx(Qo,{droppableId:t,sortableType:o,column:v},v.id):e.jsx(Go,{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",u&&"border border-muted-foreground/20"),ref:i,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(v=>p(v))})]})})}function Wo(){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 Jo(){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(Ko,{onRemoveColumn:r,sortableType:Ts,id:Es,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(ms,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(va,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(on,{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(qs,{variant:"default"})]})]})}function Zo(){const t=I.useRef(null),a=I.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog),o=s.useEditorStore(l=>l.isDevMode);I.useEffect(()=>{var l,d,m,u;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=a.current)==null||u.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(Jr,{})}),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(Fo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}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(Yo,{})})}),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(Jo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}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(z=>z.currentAIContext),[n,r]=I.useState(""),[o,i]=I.useState(null),{authToken:c}=s.useSemaphorContext(),l=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.python}),{setCardPython:u,setCardSql:h,setRunSql:p,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],v=s.useEditorStore(z=>z.userInputForAI),j=s.useEditorStore(z=>z.triggerAIRun),C=s.useEditorStore(z=>z.card),k=s.useEditorStore(z=>z.selectedDatabaseName),O=s.useEditorStore(z=>z.selectedTableName),E=s.useEditorStore(z=>z.selectedConnectionId),w=s.useEditorStore(z=>z.selectedSchemaName),y=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:D,refetch:b,data:A}=s.useDashboardCardQuery(C),{setTriggerAIRun:S,setCurrentAssitantScope:R,setCardConfig:M}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:N,selectedDatamodelId:L}=s.useEditorAside(),{messages:B,setMessages:P,reload:V,error:U,append:X,input:K,setInput:F,status:_,handleInputChange:$,handleSubmit:q,stop:Y}=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:z=>{console.log("on error",z)},onToolCall:Q,onFinish(z,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});I.useEffect(()=>{j&&v&&(X({role:"user",content:v}),S(!1))},[j,v,X,S]);async function Q({toolCall:z}){var J,ie,be,ke;if(["createChartFromSql","createForecast"].includes(z.toolName)){const ne=z.args.sql,le=z.args.python,ce=z.args.chartType;return f(ce),h(ne),u(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return l?{status:"success",sql:l,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const ne=z.args.chartType,le=z.args.queryConfig;z.args.cardConfig,f(ne),M(le),h(void 0),u(void 0);const ce=await b();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(be=ce==null?void 0:ce.data)!=null&&be.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(ke=ce==null?void 0:ce.data)==null?void 0:ke.records}}else r("Analyzing...")}}function G(z){i(J=>J?{promptTokens:J.promptTokens+z.promptTokens,completionTokens:J.completionTokens+z.completionTokens,totalTokens:J.totalTokens+z.totalTokens}:z)}function Z(z){const J=s.removeFromScopeArray(x,z);te(J)}function te(z){const J=s.sanitizeAIScope(z);R(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 z={databaseName:k||"",schemaName:w||"",tableName:O||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:N||""},J=s.dedup([...x,z]);te(J)}function se(){const z={databaseName:k||"",schemaName:w||"",tableName:O||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:N||"",datamodelId:L||""};if(!s.isInAiScopeArray([...y||[],...x],z)||x.length===0){const ie=s.dedup([...y||[],...x,z]).filter(be=>be.connectionId===z.connectionId);te(ie)}}const oe=!["ready","error"].includes(_),H=s.getErrorMessage(U);return{messages:B,setMessages:P,reload:V,append:X,input:K,setInput:F,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:R,handleInputChange:$,handleSubmit:q,stop:Y,chatStatus:_,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:H}}const si=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function yt(){const t=I.useRef(null),a=I.useRef(null),[n,r]=I.useState(!1),[o,i]=I.useState(s.isDevEnv),[c,l]=I.useState(!1),[d,m]=I.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),p=s.useDashboardStore(Y=>Y.dashboard.aiContext),f=s.useEditorStore(Y=>Y.card.dataSource),g=s.useEditorStore(Y=>Y.actions.setCardSql),x=s.useEditorStore(Y=>Y.actions.setRunSql),v=s.useEditorStore(Y=>Y.showAIDialog),j=s.useDashboardStore(Y=>Y.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:k}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:w,setMessages:y,reload:D,append:b,input:A,setInput:S,isLoading:R,handleInputChange:M,handleSubmit:T,stop:N,chatStatus:L,llmUsage:B,errorMessage:P}=ei();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:w}),I.useEffect(()=>{var Y;v&&((Y=a.current)==null||Y.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[v,f,h]);function V(Y,Q){Q==="sql"?(g(Y),x(!0)):Q==="python"&&(k(Y),x(!0))}function U(){var Y;(Y=p==null?void 0:p.selectedEntities)==null||Y[0],m(!0)}function X(){u.selectedEntities.length===0&&h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function K(Y){X();const Q={role:"user",content:Y.title+" "+Y.subtitle};b(Q)}function F(Y){X(),b({role:"user",content:Y})}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 $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const q=(A==null?void 0:A.length)===0&&(w==null?void 0:w.filter(Y=>Y.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:[$(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[_(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:U,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{C(!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:w,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:w,chatStatus:L,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[q&&!E&&e.jsx(s.Placeholders,{onClick:K,placeholders:si}),e.jsx("div",{children:q&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:F})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:S,stop:N,input:A,handleInputChange:M,handleSubmit:Y=>{X(),T(Y)},isLoading:R,onFocus:()=>{}}),B&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.promptTokens," prompt tokens,"," ",B.completionTokens," completion tokens,"," ",B.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:d,onOpenChange:m,dataSource:f||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}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 ti(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 Is(){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 Ms(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Zs=t=>{var S;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:l,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(R=>R.card.type),h=t==null?void 0:t.id,p=I.useCallback(R=>{if(!(t!=null&&t.config))return[];switch(R){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=I.useCallback((R,M)=>{if(h)switch(R){case"groupBy":{a(h,{groupByColumns:M});break}case"metrics":{a(h,{metricColumns:M});break}case"pivotBy":{a(h,{pivotByColumns:M});break}case"sortBy":{a(h,{sortByColumns:M});break}}},[h,a]),g=I.useCallback((R,M,T)=>{if(!h)return;const L=p(R)[M];if(L)switch(R){case"groupBy":n(h,L.id,{label:T});break;case"metrics":r(h,L.id,{label:T});break;case"pivotBy":o(h,L.id,{label:T});break;case"sortBy":i(h,L.id,{label:T});break}},[h,p,n,r,o,i]),x=I.useCallback((R,M)=>{if(!h)return;const N=p("metrics")[R];N&&r(h,N.id,{aggregate:M,label:s.getAggregationLabel(N.name,M)})},[h,p,r]),v=I.useCallback((R,M,T)=>{if(!h)return;const L=p("groupBy")[R];if(!L)return;const B={dateFormat:M};M==="custom"&&T?B.customFormat=T:B.customFormat=void 0,n(h,L.id,B)},[h,p,n]),j=I.useCallback((R,M)=>{if(!h)return;const N=p("groupBy")[R];N&&n(h,N.id,{granularity:M})},[h,p,n]),C=I.useCallback((R,M)=>{if(!h)return;const N=p("metrics")[R];N&&r(h,N.id,{aliasTemplate:M})},[h,p,r]),k=I.useCallback((R,M)=>{if(console.log("handleValueAliasesChange",R,M),!h)return;console.log("handleValueAliasesChange",R,M);const N=p("metrics")[R];N&&(console.log("handleValueAliasesChange",M),r(h,N.id,{valueAliases:M}))},[h,p,r]),O=I.useCallback(R=>{h&&a(h,{comparisonType:R})},[h,a]),E=I.useCallback(R=>{h&&a(h,{showTrendline:R})},[h,a]),w=I.useCallback(R=>{h&&a(h,{trendlineWindow:R})},[h,a]),y=I.useCallback(R=>{h&&a(h,{trendlineGranularity:R})},[h,a]),D=I.useCallback(R=>{h&&a(h,{targetValue:R})},[h,a]),b=I.useCallback(R=>{var V;if(!h)return;const M=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],T=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,N=ti(R,M,T);if(!N.isValid){N.showError&&Is();return}const L=s.getSmartContainerForField(R),B=p(L);if(Ms(R,B))return;const P=s.getNewField(R,L);P&&f(L,[...B,P])},[h,(S=t==null?void 0:t.config)==null?void 0:S.joinPlan,p,f]),A=I.useCallback((R,M)=>{if(!h)return;const N=p(R)[M];if(N){if(R!=="sortBy"){const L=p("sortBy"),B=L.filter(P=>!(P.name===N.name&&P.qualifiedEntityName===N.qualifiedEntityName));B.length!==L.length&&a(h,{sortByColumns:B})}switch(R){case"groupBy":c(h,N.id);break;case"metrics":l(h,N.id);break;case"pivotBy":d(h,N.id);break;case"sortBy":m(h,N.id);break}}},[h,p,c,l,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:C,handleValueAliasesChange:k,removeField:A,handleFieldClick:b,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:D,cardType:u}};function ni({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function ai({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=s.useSortable({id:t.id}),[l,d]=I.useState(!1),m=s.useEditorStore(g=>g.card),{handleFieldClick:u}=Zs(m),h={transform:s.CSS.Transform.toString(o),transition:i};s.getDataType(t.dataType);const p=g=>{const x=(g||"").toLowerCase();switch(s.getDataType(x)){case"number":return $e;case"date":return s.Calendar;case"boolean":return ts;case"json":return it;case"geo":return lt;default:return Qe}},f=g=>{const x=(g||"").toLowerCase(),v=s.getDataType(x);return v==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):v==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx($e,{className:"h-3 w-3"})}):v==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):v==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ts,{className:"h-3 w-3"})}):v==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(it,{className:"h-3 w-3"})}):v==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(lt,{className:"h-3 w-3"})}):v==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Dt,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[f(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${l?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ni,{field:t})})]})})]}),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(Lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{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]=I.useState(""),[n,r]=I.useState("all"),o=s.useEditorStore(k=>k.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:l,error:d}=s.useColumns(),m=i.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const O=s.getDataType(k.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(k=>u(k)===n)).reduce((k,O)=>{const E=O.qualifiedEntityName||"Other Fields";return k[E]||(k[E]={label:s.toLabel(O.entityName),fields:[]}),k[E].fields.push(O),k},{}),g=Object.keys(p),x=m.filter(k=>u(k)==="dimensions").length,v=m.filter(k=>u(k)==="metrics").length,j=m.filter(k=>u(k)==="calculated").length,C=m.length>0;return l?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!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.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>a(k.target.value)})]}),C&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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(Dt,{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(([k,O])=>{const E=c.find(w=>w.entityName===k)||{entityName:k,label:O.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:E.label||E.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(w=>e.jsx(ai,{field:w},w.id))})})]},k)})}),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]=I.useState(t),[o,i]=I.useState(new Set),c=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,y={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,y]}),i(new Set([...o,y.id]))},l=w=>{r({...n,joins:n.joins.filter(y=>y.id!==w)}),i(new Set([...o].filter(y=>y!==w)))},d=(w,y)=>{var S,R;const D=n.joins.find(M=>M.id===w);if(!D)return;const b={...D,...y},A=n.joins.map(M=>M.id===w?b:M);if((S=b.source)!=null&&S.name&&((R=b.target)!=null&&R.name)&&b.joinKeyGroups[0].keys.length===0){const M=a.find(B=>{var P;return B.name===((P=b.source)==null?void 0:P.name)}),T=a.find(B=>{var P;return B.name===((P=b.target)==null?void 0:P.name)}),N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},L=[...b.joinKeyGroups];L[0]={...L[0],keys:[N]},b.joinKeyGroups=L,A[A.findIndex(B=>B.id===w)]=b}r({...n,joins:A})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:l,updateJoin:d,moveJoinUp:w=>{const y=n.joins.findIndex(D=>D.id===w);if(y>0){const D=[...n.joins],b={...D[y]},A={...D[y-1]};D[y]=A,D[y-1]=b,D.forEach((R,M)=>{R.sequence=M+1});const S={...n,joins:D};r(S)}},moveJoinDown:w=>{const y=n.joins.findIndex(D=>D.id===w);if(y<n.joins.length-1){const D=[...n.joins],b={...D[y]},A={...D[y+1]};D[y]=A,D[y+1]=b,D.forEach((R,M)=>{R.sequence=M+1});const S={...n,joins:D};r(S)}},toggleJoinExpansion:w=>{const y=new Set(o);y.has(w)?y.delete(w):y.add(w),i(y)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const y=n.joins.findIndex(b=>b.id===w);if(y===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,y).forEach(b=>{D.add(b.source.name),D.add(b.target.name)}),a.filter(b=>D.has(b.name))},getAvailableTargetEntities:w=>a.filter(y=>y.name!==w),addJoinKeyGroup:w=>{const y=n.joins.find(b=>b.id===w);if(!y)return;const D=[...y.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(w,{joinKeyGroups:D})},updateGroupOperator:(w,y,D)=>{const b=n.joins.find(S=>S.id===w);if(!b)return;const A=[...b.joinKeyGroups];A[y]={...A[y],operator:D},d(w,{joinKeyGroups:A})},removeJoinKeyGroup:(w,y)=>{const D=n.joins.find(A=>A.id===w);if(!D)return;const b=[...D.joinKeyGroups];b.splice(y,1),d(w,{joinKeyGroups:b})},addJoinKey:(w,y)=>{const D=n.joins.find(M=>M.id===w);if(!D)return;const b=a.find(M=>M.name===D.source.name),A=a.find(M=>M.name===D.target.name),S=[...D.joinKeyGroups],R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(b==null?void 0:b.name)||"",entityName:(b==null?void 0:b.name)||"",entityType:(b==null?void 0:b.type)||"table"},target:{id:`target-${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"},operator:"="};S[y]={...S[y],keys:[...S[y].keys,R]},d(w,{joinKeyGroups:S})},updateJoinKey:(w,y,D,b,A)=>{const S=n.joins.find(L=>L.id===w);if(!S)return;const R=a.find(L=>L.name===S.source.name),M=a.find(L=>L.name===S.target.name),T=[...S.joinKeyGroups],N=T[y].keys[D];b==="sourceColumnName"&&R?T[y].keys[D]={...N,source:{...N.source,name:A}}:b==="targetColumnName"&&M?T[y].keys[D]={...N,target:{...N.target,name:A}}:b==="operator"&&(T[y].keys[D]={...N,operator:A}),d(w,{joinKeyGroups:T})},removeJoinKey:(w,y,D)=>{const b=n.joins.find(S=>S.id===w);if(!b)return;const A=[...b.joinKeyGroups];A[y].keys.splice(D,1),d(w,{joinKeyGroups:A})},generateSQLPreview:()=>{const w=[...n.joins].sort((b,A)=>b.sequence-A.sequence),y=n.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
430
|
-
FROM ${
|
|
428
|
+
`;C(q)}function B(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Kr,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.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(Hr,{})}),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 V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:D||b,onClick:()=>{E()},className:"h-8 shrink-0",size:"sm",children:[D||b?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(on,{sql:v==null?void 0:v.sql,error:N,onDebugWithAssistant:L}),e.jsx(ms,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:q=>n(q),className:"",size:"sm",children:e.jsx(Gr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{}),e.jsx(qs,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),B()]}),V()]})}function Xr({data:t}){var c;const[a,n]=I.useState([]),o=Object.keys(t[0]).map(l=>({accessorKey:l,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[l,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),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 C,k,R,T,w,v,D,b,A,S,O;const[a,n]=I.useState(!1),[r,o]=I.useState([]),{authToken:i}=s.useSemaphorContext(),c=s.getTokenParams(i==null?void 0:i.accessToken),l=s.useDashboardStore(M=>M.themeStyle),d={colors:((k=(C=l==null?void 0:l.chart)==null?void 0:C.dataset)==null?void 0:k.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:m}=s.useCustomVisual(((T=t.customCardPreferences)==null?void 0:T.url)||""),u=((w=t.customCardPreferences)==null?void 0:w.visualType)||"single",h=s.useEditorStore(M=>M.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:f}=s.useDashboardCardQuery(t),j=I.useCallback((M,E)=>{o(N=>({...N,[M]:E}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const x=m((D=t.customCardPreferences)==null?void 0:D.componentName);function y(M){n(M)}const g=Object.keys(((b=t.customCardPreferences)==null?void 0:b.dataInputCardIds)||{}).map(M=>{var L,B,P;const E=(B=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:B[M].cardId,N=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===E);return N||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(I.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&u==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(A=t.customCardPreferences)==null?void 0:A.settings,onDataChange:j,data:(f==null?void 0:f.records)||[]}),x&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(M=>{var L,B,P;const E=(B=(L=t.customCardPreferences)==null?void 0:L.dataInputCardIds)==null?void 0:B[M].cardId,N=(P=h==null?void 0:h.cards)==null?void 0:P.find(V=>V.id===E);if(N)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:M,card:N},N.id+M)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:j,settings:g.map(M=>{var E;return(E=M==null?void 0:M.customCardPreferences)==null?void 0:E.settings}),data:g.map(M=>M!=null&&M.id?r==null?void 0:r[M.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function un({className:t,...a}){var D;const n=s.useEditorStore(b=>b.card),r=s.isExplorerCard(n),o=((D=n.customCardPreferences)==null?void 0:D.showCardHeader)??!0,i=s.useEditorStore(b=>b.frame),c=s.useDashboardStore(b=>b.dashboard.filters),l=s.useEditorStore(b=>b.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),m=c==null?void 0:c.find(b=>b.id===i.filterId),{data:u,isLoading:h,isFetching:p,errorMessage:f,pagination:j,refetch:x}=s.useDashboardCardQuery(n),{setCard:y,updateCardInFrame:g}=s.useEditorActions(),{data:C}=s.useTopoJson(n),k=I.useMemo(()=>n.type==="pivotTable"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0?s.getPivotTableConfig({card:n,data:{records:(u==null?void 0:u.records)||[],columnSubtotalMeta:u==null?void 0:u.columnSubtotalMeta,subtotalColumns:u==null?void 0:u.subtotalColumns,pivotSchema:(u==null?void 0:u.pivotSchema)||[],groupByColumns:u==null?void 0:u.groupByColumns}}):null,[n,u==null?void 0:u.records,u==null?void 0:u.columnSubtotalMeta,u==null?void 0:u.subtotalColumns,u==null?void 0:u.pivotSchema,u==null?void 0:u.groupByColumns]),R=(b,A)=>{var O,M;const S={...n,paginationConfig:{page:b+1,pageSize:A}};y(S),g(S),n.sql&&((M=(O=n.preferences)==null?void 0:O.tablePrefs)!=null&&M.enableDevModePagination)&&l(!0)},T=I.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:C}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,C]);function w(b){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Zr,{card:b})})}function v(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!p)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return w(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&T)return e.jsx(e.Fragment,{children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:T})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(u==null?void 0:u.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||p})});if(n.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:k.data,options:k.options,onAggregationChange:b=>{const A=s.handleAggregationChange(b,n.config),S={...n,config:A};y(S),g(S)},onAggregationLabelChange:b=>{const A=s.handleAggregationLabelChange(b,n.config),S={...n,config:A};y(S),g(S)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(u==null?void 0:u.records)||[],groupByColumns:u==null?void 0:u.groupByColumns,pivotSchema:u==null?void 0:u.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:b=>{const A=s.handleAggregationChange(b,n.config),S={...n,config:A};y(S),g(S)},isLoading:h||p})})}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:b=>y({...n,title:b}),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:b=>y({...n,description:b}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:m.title||m.column,onSave:b=>d({...m,title:b}),children:e.jsx(s.Label,{children:m.title})}),e.jsx(s.FilterComponent,{filter:m})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const bs=({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(bs,{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(bs,{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(bs,{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]=I.useState(!1),[n,r]=I.useState(""),[o,i]=I.useState(""),[c,l]=I.useState(""),[d,m]=I.useState(""),u=s.useEditorStore(T=>T.card),h=s.useEditorStore(T=>T.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:f}=s.useDashboardCardQuery(u),{data:j}=s.useTopoJson(u),{setCardCustomCfg:x,setCustomVisualCode:y}=s.useEditorActions(),g=T=>{var w,v;return JSON.stringify({...T,data:{...T.data,datasets:(v=(w=T.data)==null?void 0:w.datasets)==null?void 0:v.map(D=>({...D,data:[]}))}},null,2)},C=()=>{var w,v;if(!((w=f==null?void 0:f.records)!=null&&w.length))return;const T=s.createChartConfig({card:u,data:f.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:j});if(T){r(g(T)),l(((v=u.preferences)==null?void 0:v.customVisualCode)||"");const D=s.merge(T,h);i(g(D))}},k=()=>{try{if(c&&y(c),o){const T=JSON.parse(o),w=s.getObjectDiff(JSON.parse(n),T);x(w),m("")}}catch{m("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:C,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.FallbackVisual,children:e.jsx(un,{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:!!h,onReset:()=>{i(n),x(null)},onApply:k,onClose:()=>a(!1)})]})]})}function hs(t){const[a,n]=I.useState(null);return a}function Ys(){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]=I.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=s.useEditorActions(),{data:l}=Ys();function d(m,u){r(null),o({}),i(m),u&&c({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),t==null||t()}return I.useEffect(()=>{(async()=>{var u;if(l){const p=(await Promise.all((u=l==null?void 0:l.plugins)==null?void 0:u.map(async f=>(await s.loadManifest(f.value)).visuals.map(y=>({name:y.name,icon:y.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((m,u)=>e.jsx(ro,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+u))})]})}const ro=({text:t,icon:a,onClick:n})=>{const r=hs(),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 Gs(t){return Oe({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 Oe({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 Hs(t){return Oe({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 Oe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Ks(t){return Oe({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 Ws(t){return Oe({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 mn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(u=>u.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function d(u,h){i(null),r({}),n(u),["custom","text","map"].includes(u)&&(o(!0),l(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Ve,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(cs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(us,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,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:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Bs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(wt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Fs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ge,{className:s.cn("size-5",a)})})]})}function io({chartType:t,className:a,customIcon:n,componentName:r}){const o=hs();switch(t){case"bar":return e.jsx(cs,{className:a});case"line":return e.jsx(ds,{className:a});case"pie":return e.jsx(us,{className:a});case"radar":return e.jsx(Bs,{className:a});case"scatter":return e.jsx(Os,{className:a});case"bubble":return e.jsx(Hs,{className:a});case"doughnut":return e.jsx(Rs,{className:a});case"stackedBar":return e.jsx(As,{className:a});case"stackedLine":return e.jsx(Ks,{className:a});case"polarArea":return e.jsx(Gs,{className:a});case"funnel":return e.jsx(Qs,{className:a});case"tornado":case"pyramid":return e.jsx(zs,{className:a});case"range":return e.jsx(Ls,{className:a});case"kpi":return e.jsx(Ws,{className:a});case"text":return e.jsx(Qe,{className:a});case"map":return e.jsx(Fs,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ge,{className:a});default:return e.jsx(Ve,{className:a})}}function hn({variant:t="ghost"}){var i,c;const[a,n]=I.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(mn,{onChartTypeChange:()=>n(!1)}),e.jsx(ao,{onChartTypeChange:()=>n(!1)})]})]})}const We="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function jt(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 L,B,P,V,q,X;const[t,a]=I.useState(!1),n=s.useEditorStore(K=>{var $;return($=K.card)==null?void 0:$.preferences}),r=s.useEditorStore(K=>{var $;return($=K.card)==null?void 0:$.type}),o=s.getNumberAxis(n,{}),[i,c]=I.useState(jt(n,r)),[l,d]=I.useState(((P=(B=(L=n==null?void 0:n.chartOptions)==null?void 0:L.scales)==null?void 0:B[o])==null?void 0:P.min)||""),[m,u]=I.useState(((X=(q=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:q[o])==null?void 0:X.max)||""),[h,p]=I.useState(l||m?"custom":"auto"),[f,j]=I.useState(""),[x,y]=I.useState(0),[g,C]=I.useState(""),[k,R]=I.useState(""),[T,w]=I.useState(""),v=s.useEditorStore(K=>K.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),b=s.useEditorStore(K=>K.card),A=["pie","doughnut","polarArea","funnel"].includes(r);I.useEffect(()=>{var K,$,F,U,_,Y,Q,G,Z,te,ae,se,oe,H;c(jt(n,r)),d(((F=($=(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales)==null?void 0:$[o])==null?void 0:F.min)===0?0:""),u(((Y=(_=(U=n==null?void 0:n.chartOptions)==null?void 0:U.scales)==null?void 0:_[o])==null?void 0:Y.max)||""),j(((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)||""),y(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),C(((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)||""),w(((H=n==null?void 0:n.numberAxisFormat)==null?void 0:H.locale)||"")},[t,n,o,r]);function S(K,$){return $===""||/^[0-9\b]+$/.test($)?Number($):Number(K)}function O(){const K=[...new Set(s.LOCALE_CURRENCY_PAIRS.map($=>$.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:k||"none",onValueChange:$=>R($==="none"?"":$),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),K.map($=>e.jsx(s.SelectItem,{value:$,children:$},$))]})})]}),e.jsxs(s.Select,{value:T,onValueChange:$=>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,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map($=>e.jsx(s.SelectItem,{value:$.locale,children:$.locale},$.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:$=>y(Number($.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${We}`})]})]})}function M(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:A,value:i,onValueChange:K=>c(K),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),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:A,id:"scale-option",value:h,onValueChange:K=>p(K),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&i=="linear"&&E()]})}function E(){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:K=>d($=>S($,K.target.value)),className:`col-span-1 h-8 w-full ${We}`}),e.jsx(s.Input,{value:m,onChange:K=>u($=>S($,K.target.value)),id:"max",className:`col-span-1 h-8 w-full ${We}`})]}),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:K=>j($=>S($,K.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${We}`})]})]})}function N(){var U;let K={};h==="custom"&&(K={min:l,max:m,ticks:{stepSize:f}});const $={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(U=n==null?void 0:n.chartOptions)==null?void 0:U.scales,[o]:{type:i,...i==="linear"?K:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:k,locale:T}};console.log($),v($);const F={...b,preferences:$};D(F)}return e.jsxs(s.Popover,{onOpenChange:K=>a(K),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(ta,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),M(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:N,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function co(){const t=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.position}),a=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.align}),n=s.useEditorStore(l=>{var d,m,u,h;return(h=(u=(m=(d=l.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:u.legend)==null?void 0:h.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(ha,{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(qn,{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(Bn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Fn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(zn,{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(dt,{className:"size-4"}):e.jsx(ct,{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(dt,{className:"size-4"}):e.jsx(ct,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function xn(){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(da,{className:"size-4"}),r==="x"&&e.jsx(Xn,{className:"size-4"}),r==="y"&&e.jsx(Sa,{className:"size-4"}),r==="none"&&e.jsx(Ea,{className:"size-4"})]})]}):null}function mo(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},l=j=>{j.preventDefault()},d=(j,x)=>{const y=j.dataTransfer.getData("tabIndex");if(y===x.toString())return;const g=Array.from(t.cards),[C]=g.splice(parseInt(y),1);g.splice(x,0,C),n({...t,cards:g})};function m(j){const x=t.cards.filter(C=>C.id!==j),y=x[0],g={...t,cards:x,activeCardId:y.id};n(g),r(y.id),o(y)}function u(j,x){const y={...t,cards:[...t.cards,x],activeCardId:j.id};n(y),r(x.id)}function h(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(a,j)}function p(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};u(j,x)}function f(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:y}),i({...x,displayTab:y})},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(na,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,x),onDragOver:l,onDrop:y=>d(y,x),className:"",value:j.id,children:[f(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{o({...a,tabTitle:y}),i({...a,tabTitle:y})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>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:h,children:e.jsx(ea,{className:"h-4 w-4"})})]})})}function pn(){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:m,isLoading:u,isFetching:h}=s.useDashboardCardQuery(a);function p(x){const y=t.cards.find(g=>g.id===x);if(y!=null&&y.sql){r||l(!0),i(x);return}if(y!=null&&y.queryConfig){r&&l(!1),f(x),i(x);return}r||f(x),i(x)}function f(x){const y={...t,cards:t.cards.map(C=>C.id===a.id?a:C),activeCardId:x};o(y);const g=y.cards.find(C=>C.id===x);g.sql&&d(!0),c(g)}function j(){return a.type==="kpi"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:m==null?void 0:m.records,isPending:u||h})})}):a.type==="text"?u||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(un,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:j()},x.id)),e.jsx(mo,{})]})}function Je({children:t}){var R,T;s.useEditorStore(w=>w.frame);const a=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),o=s.useDashboardStore(w=>w.isVisualEditing),i=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:l,setActiveTabCardId:d,runAssistant:m,setIsDevMode:u,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:f,isFetching:j,errorMessage:x,refetch:y}=s.useDashboardCardQuery(a);function g(){const w=JSON.stringify(p==null?void 0:p.records,null,2),v=new Blob([w],{type:"application/json"}),D=URL.createObjectURL(v),b=document.createElement("a");b.href=D,b.download=`${a.title}.json`,b.click()}function C(){const v=[Object.keys(p==null?void 0:p.records.reduce((S,O)=>({...S,...O}),{})).join(","),...((p==null?void 0:p.records)||[]).map(S=>Object.values(S).join(","))].join(`
|
|
429
|
+
`),D=new Blob([v],{type:"text/csv"}),b=URL.createObjectURL(D),A=document.createElement("a");A.href=b,A.download=`${a.title}.csv`,A.click()}function k(){const w=`Can you get the documentation for ${a.type} chart?`;m(w)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(hn,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(Hn,{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:C,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:g,children:e.jsx(ra,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(xn,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((T=(R=a.preferences)==null?void 0:R.tablePrefs)==null?void 0:T.enableDevModePagination)??!1,onCheckedChange:w=>{var v;h({...a.preferences,tablePrefs:{...(v=a.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:w}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xo,{})]}),r?e.jsx(pn,{}):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:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(Xr,{data:(p==null?void 0:p.records)||[]}),x&&e.jsx(an,{error:x})]})]})]}):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,y;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=Ys(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(g=>g.card),o=s.useEditorStore(g=>g.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)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(g=>g.name===(t==null?void 0:t.componentName));function u(g,C){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:C,hookRef:null}};c({...t,dataInputCardIds:R})}function h(g){var k,R;const C=(k=o==null?void 0:o.cards)==null?void 0:k.filter(T=>{var w;return((w=T==null?void 0:T.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(R=g==null?void 0:g.dataInputs)==null?void 0:R.map((T,w)=>{var v,D;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:C||[],value:((D=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[w])==null?void 0:D.cardId)||"",onValueChange:b=>u(w,b)})]},w+Math.random())})})}function p(g,C,k=[],R=""){var T,w;return t?g==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((T=t==null?void 0:t.settings)==null?void 0:T[C])||R,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:v.target.value}})}},C):g==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:k,value:((w=t==null?void 0:t.settings)==null?void 0:w[C])||R,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[C]:v}})}}):null:null}function f(g){const C=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([k,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),p(R.ui,k,R.options,R.defaultValue)]},k))})}function j(g){t&&c({...t,visualType:g,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(Gn,{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:g=>c({...t||{url:"",componentName:""},url:g})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:l&&e.jsx(he,{icon:e.jsx(Zn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.filter(g=>g.type===i).map(g=>({value:g.name,label:g.name})))||[],value:t.componentName,onValueChange:g=>{console.log("changing value",g),c({...t,componentName:g})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function Re(){const[t,a]=I.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(m=>m.actions),i=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var u;return(u=m.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),I.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(m,u){var h,p;u?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):o({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(o({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(f=>f.columnIndex!==m)}),a(f=>{const j=[...f];return j[m]=!1,j}))}function l(m,u){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(f=>f.columnIndex===m?{...f,expression:u.target.value}:f);o({...n,onClickFilter:h})}function d(m){var u,h,p,f;if(t!=null&&t[m]||(h=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(j=>j.columnIndex===m))!=null&&h.expression)return e.jsx(s.Input,{value:(f=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===m))==null?void 0:f.expression,onChange:j=>l(m,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),i==null?void 0:i.map((m,u)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===u)),onCheckedChange:f=>c(u,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===u))&&e.jsx(s.Pencil,{onClick:()=>{a(f=>{const j=[...f];return j[u]=!f[u],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(u)]})},m)})]})}function fo({idx:t}){var l;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.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,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const u={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:u}]});else{const h={...i};h.datalabels=u;const p=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Lt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(xa,{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(fa,{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(pa,{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 Js({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 fn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,u,h;return(h=(u=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:u.chartOptions)==null?void 0:h.indexAxis}),{data: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:gn(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,m)=>e.jsx(jn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function gn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function jn({col:t,idx:a,className:n,iconClassName:r,children:o}){const i=s.useEditorStore(u=>{var h;return(h=u.card)==null?void 0:h.preferences}),c=s.useEditorStore(u=>{var h,p;return(p=(h=u.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),l=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:d}=s.useEditorStore(u=>u.actions);function m(u){if(!l)d({...i,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const h={...l};h.type=u==="area"?"line":u,h.fill=u==="area"?"origin":"";const p=c==null?void 0:c.map(f=>f.idx===a?h: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(Js,{className:"max-w-[100px]",title:t,children:gn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(cs,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ds,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(kt,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fo,{idx:a})]})]})}function yn(){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:m,tableName:u,connectionType:h}=s.useEditorAside();function p(f,j="dashboard"){var v;const x=s.fmt(f.column_name),y=s.fmt(n||""),g=s.fmt(r||""),C=s.fmt(u);let k=s.getQualifiedTableName({schemaName:g,tableName:C,connectionType:h,databaseName:y}),R=`${k}.${x}`;const T=(v=m==null?void 0:m.find(D=>D.id===a))==null?void 0:v.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${T}.${x}`,k=`${s.DATAMODEL_NAMESPCACE}.${T}`);const w=i==null?void 0:i.find(D=>D.column===R&&D.table===C&&(D.database===y||D.database===n));if(w)d(w.id),l(w.id);else{const D=s.v4();return u==="api"&&t?(c({location:j,id:D,column:R,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(f.data_type,k,x)}),D):(c({id:D,location:j,column:R,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(f.data_type,k,x)}),D)}}return{assignFilter:p}}function Ue(){const t=s.useDashboardStore(l=>l.dashboard.filters),a=s.useEditorStore(l=>l.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=yn();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 m=d===o?"":d;i(m),r(!1),m&&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(fn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ue,{})]})]})]})})}function xs(){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 u;const d={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins,...d}}};r(m)}function i(){var l,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(l=n==null?void 0:n.chartOptions)==null?void 0:l.plugins)==null?void 0:d.datalabels)==null?void 0:m.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(xs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ue,{})]})]})]})})}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(xs,{}),e.jsx(Re,{}),e.jsx(Ue,{})]})]})}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 Ns({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,m,u,h,p,f,j,x,y,g,C,k,R,T,w,v,D,b;const t=s.useEditorStore(A=>A.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=I.useState(((h=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(A=>({label:A,value:A}))||[],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(Ns,{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(Ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:l,onValueChange:A=>{console.log("value",A),o({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.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:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Do,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:To,value:((g=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ns,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:A=>{var S;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(T=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:w[0])||0,onChange:A=>{var S,O,M,E;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(A.target.value),((E=(M=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:E[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((b=(D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:b[1])||0,onChange:A=>{var S,O,M,E;o({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((E=(M=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:E[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Re,{})]})}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 Xe({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(xs,{}),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(Re,{}),e.jsx(Ue,{})]})]})]})})}function Mo(){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(fn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Ue,{})]})]})]})})}function Ao({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(Re,{}),e.jsx(Ue,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}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."]})]}),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 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."]})]}),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 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 Fo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Mo,{});case"tornado":case"pyramid":return e.jsx(Xe,{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(Xe,{docContent:Oo,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Xe,{cardType:n});case"bubble":case"scatter":return e.jsx(vo,{cardType:n});case"table":return e.jsx(Ao,{cardType:n});case"text":return e.jsx(Xe,{docContent:Ro,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 vn({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 Bo=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ye,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ia,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(_n,{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 zo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Bo;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:Ke(t.name,o)};a(t.id,i)}return e.jsx(vn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Po=[{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 Vo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:_e(t.name,r)};a(t.id,o)}return e.jsx(vn,{column:t,functions:Po,onFunctionChange:r=>n(r),label:"Granularity"})}function _o({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=I.useMemo(()=>{let l=[];(n===Ie||n===Me||n===Ae)&&(l=r);const d=l==null?void 0:l.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),i=[{id:t.name,value:t.name}];function c(l){const d=r==null?void 0:r.find(m=>{var u;return m.column_name===((u=l[0])==null?void 0:u.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 bn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,u;return(u=(m=d.card)==null?void 0:m.config)==null?void 0:u.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(jn,{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(xs,{})]})}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]=I.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:l,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:u,setNodeRef:h,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(p),transition:f}:void 0,y=s.isTextDataType(t.type);function g(w){const v=s.isNumberDataType(w.data_type),D=s.isTextDataType(w.data_type),b=s.isDateDataType(w.data_type),A=v?"number":D?"string":b?"date":"string";if(r===Ie){if(D){const S={id:t.id,name:w.column_name,type:A,role:"groupby"};c(t.id,S)}if(b){const S={id:t.id,name:w.column_name,type:A,role:"groupby",label:_e(w.column_name,"month"),granularity:"month"};c(t.id,S)}}if(r===Ae){if(D){const S={id:t.id,name:w.column_name,type:A,role:"groupby"};d(t.id,S)}if(b){const S={id:t.id,name:w.column_name,type:A,label:_e(w.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,S)}}if(r===Me){const S={id:t.id,name:w.column_name,type:A,role:"metric",label:Ke(w.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};l(t.id,S)}}function C(){if(r===Me)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(bn,{column:t})})}function k(){const w=s.isDateDataType(t.type);if(r===Me)return e.jsx(zo,{column:t});if((r===Ie||r===Ae)&&w)return e.jsx(Vo,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Ae)&&y}),children:e.jsx(_o,{col:t,onChange:g,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(ka,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[T(),k(),R()]}),o&&C()]}),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 Cs({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var x,y;const{setNodeRef:c,isOver:l,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),u=s.useEditorStore(g=>{var C;return(C=g.card)==null?void 0:C.type}),h=l||((y=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:y.type)===o,p=m?r:n,f=o===rs?"Rows":o===os?"Pivot Columns":"Columns";function j(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),u!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),j(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(g=>g.id===tn.id?e.jsx(qo,{},g.id):e.jsx(Uo,{droppableId:t,type:o,column:g,onRemoveColumn:i},g.id))})]})})}function qo(){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 Nn({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}}),m=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:m,children:t})}function $o(){const t=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.orderBy})||[],a=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=s.useEditorStore(g=>{var C;return(C=g.card.queryConfig)==null?void 0:C.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(Yn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Vn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Pn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(g=>!t.some(C=>C.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,C){const k=f(g);return k?k.role==="metric"?C==="asc"?m:u:C==="asc"?l:d:null}function f(g){return c.find(C=>C.id===g)}function j(g){const C=t.find(k=>k.columnId===g);if(C){const k={...C,direction:C.direction==="asc"?"desc":"asc"};i(k)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function y(g){const C=t.find(k=>k.columnId===g);C&&o(C)}return e.jsx(s.SortableContext,{items:t.map(g=>$e(g.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var C,k;return e.jsx(Nn,{id:$e(g.columnId),type:Us,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Js,{className:"w-[175px] text-sm",children:((C=f(g.columnId))==null?void 0:C.label)||((k=f(g.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:g.direction==="asc"?"Ascending":"Descending",onClick:()=>j(g.columnId),className:"rounded-sm p-0",children:p(g.columnId,g.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>y(g.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"})})})]})},g.columnId)},$e(g.columnId))})]})})}function Yo(){const t=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(y=>y.card.type),n=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.metricColumns)||[]}),o=s.useDndStore(y=>y.previewMetricColumns),i=s.useEditorStore(y=>{var g;return((g=y.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:l,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function u(y){l(y)}function h(y){d(y)}function p(y){m(y)}let f="Group By",j="Metrics",x="Stack By";return a==="table"&&(f="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(mn,{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(Cs,{onRemoveColumn:u,sortableType:rs,id:Ie,label:f,columns:t,previewColumns:n}),e.jsx(Cs,{onRemoveColumn:p,sortableType:os,id:Ae,label:x,columns:i,previewColumns:c}),e.jsx(Cs,{onRemoveColumn:h,sortableType:ks,id:Me,label:j,columns:r,previewColumns:o}),e.jsx($o,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Xs({children:t,column:a,id:n,sortableType:r,className:o}){const[i,c]=I.useState(!1),{removeEditorFilter:l,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(h=>{var p,f;return(f=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:f.some(j=>j.filterColumnName===a.name)});function u(h){l(h)}return e.jsx(Nn,{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}),m&&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:()=>u(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 Go({column:t,sortableType:a}){const n=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var R,T;return(T=(R=k.card)==null?void 0:R.queryConfig)==null?void 0:T.filters}),o=s.useEditorStore(k=>{var R,T;return(T=(R=k.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:T.find(w=>w.name===t.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:l}=s.useEditorAside(),d=I.useMemo(()=>{var k;return(k=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),m=I.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:u}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:i,dataType:t.type},{data:p,isLoading:f,isFetching:j,isError:x}=s.useFilterQuery(h),y=I.useMemo(()=>{var R;return h.column?(R=p==null?void 0:p.records)==null?void 0:R.map(T=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return T[w]===void 0&&(w=w.toLowerCase()),{id:T[w],value:T[w]}}):[]},[p,h.column]);function g(k){const R=k.map(T=>T.id);u(t.name,R)}function C(){return f||j?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(Ho,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:y,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Xs,{className:"w-60",id:t.id,sortableType:a,column:t,children:C()})}function Ho({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]=I.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:m,isError:u,data:h}=s.useFilterQuery(l),p=h==null?void 0:h.records,{dateRange:f,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:y}=s.useEditorActions();function g(R){var w,v;const T={gte:(w=R==null?void 0:R.from)==null?void 0:w.toISOString(),lte:(v=R==null?void 0:R.to)==null?void 0:v.toISOString()};y(t.name,T)}function C(){y(t.name,null,!0),j(x)}function k(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:l.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:j,onApply:g,onClear:C}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Xs,{className:"w-72",id:t.id,sortableType:a,column:t,children:k()})}function Ko({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var j,x;const{setNodeRef:i,isOver:c,over:l}=s.useDroppable({id:t}),d=s.useDndStore(y=>y.activeId),m={},u=c||((x=(j=l==null?void 0:l.data)==null?void 0:j.current)==null?void 0:x.type)===o;function h(){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(y){const g=s.isDateDataType(y.type);return y.id===tn.id?e.jsx(Xs,{id:y.id,sortableType:o,column:y,children:e.jsx(Wo,{})},y.id):g?e.jsx(Qo,{droppableId:t,sortableType:o,column:y},y.id):e.jsx(Go,{droppableId:t,sortableType:o,column:y},y.id)}const f=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:i,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(y=>p(y))})]})})}function Wo(){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 Jo(){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(Ko,{onRemoveColumn:r,sortableType:Es,id:Ts,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(ms,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(va,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(on,{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(qs,{variant:"default"})]})]})}function Zo(){const t=I.useRef(null),a=I.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog),o=s.useEditorStore(l=>l.isDevMode);I.useEffect(()=>{var l,d,m,u;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(u=a.current)==null||u.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(Jr,{})}),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(Fo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}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(Yo,{})})}),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(Jo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}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(z=>z.currentAIContext),[n,r]=I.useState(""),[o,i]=I.useState(null),{authToken:c}=s.useSemaphorContext(),l=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.sql}),d=s.useEditorStore(z=>z.isDevMode),m=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.python}),{setCardPython:u,setCardSql:h,setRunSql:p,switchCardType:f,setQueryConfig:j}=s.useEditorActions(),x=s.useEditorStore(z=>z.currentAssitantScope)||[],y=s.useEditorStore(z=>z.userInputForAI),g=s.useEditorStore(z=>z.triggerAIRun),C=s.useEditorStore(z=>z.card),k=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),T=s.useEditorStore(z=>z.selectedConnectionId),w=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:D,refetch:b,data:A}=s.useDashboardCardQuery(C),{setTriggerAIRun:S,setCurrentAssitantScope:O,setCardConfig:M}=s.useEditorActions(),{selectedDatamodelName:E,connectionType:N,selectedDatamodelId:L}=s.useEditorAside(),{messages:B,setMessages:P,reload:V,error:q,append:X,input:K,setInput:$,status:F,handleInputChange:U,handleSubmit:_,stop:Y}=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:z=>{console.log("on error",z)},onToolCall:Q,onFinish(z,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});I.useEffect(()=>{g&&y&&(X({role:"user",content:y}),S(!1))},[g,y,X,S]);async function Q({toolCall:z}){var J,ie,Ne,Te;if(["createChartFromSql","createForecast"].includes(z.toolName)){const ne=z.args.sql,le=z.args.python,ce=z.args.chartType;return f(ce),h(ne),u(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(z.toolName==="getTableColumns")r("Getting table columns...");else{if(z.toolName==="getUserSql")return l?{status:"success",sql:l,python:m||""}:{status:"error",message:"No SQL found"};if(z.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(z.toolName==="generateQueryConfig"){r("Generating query config...");const ne=z.args.chartType,le=z.args.queryConfig;z.args.cardConfig,f(ne),M(le),h(void 0),u(void 0);const ce=await b();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}:(Ne=ce==null?void 0:ce.data)!=null&&Ne.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(Te=ce==null?void 0:ce.data)==null?void 0:Te.records}}else r("Analyzing...")}}function G(z){i(J=>J?{promptTokens:J.promptTokens+z.promptTokens,completionTokens:J.completionTokens+z.completionTokens,totalTokens:J.totalTokens+z.totalTokens}:z)}function Z(z){const J=s.removeFromScopeArray(x,z);te(J)}function te(z){const J=s.sanitizeAIScope(z);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 z={databaseName:k||"",schemaName:w||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(E),connectionId:T||"",connectionType:N||""},J=s.dedup([...x,z]);te(J)}function se(){const z={databaseName:k||"",schemaName:w||"",tableName:R||"",datamodelName:s.resolveDatamodelName(E),connectionId:T||"",connectionType:N||"",datamodelId:L||""};if(!s.isInAiScopeArray([...v||[],...x],z)||x.length===0){const ie=s.dedup([...v||[],...x,z]).filter(Ne=>Ne.connectionId===z.connectionId);te(ie)}}const oe=!["ready","error"].includes(F),H=s.getErrorMessage(q);return{messages:B,setMessages:P,reload:V,append:X,input:K,setInput:$,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:U,handleSubmit:_,stop:Y,chatStatus:F,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:H}}const si=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function yt(){const t=I.useRef(null),a=I.useRef(null),[n,r]=I.useState(!1),[o,i]=I.useState(s.isDevEnv),[c,l]=I.useState(!1),[d,m]=I.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),p=s.useDashboardStore(Y=>Y.dashboard.aiContext),f=s.useEditorStore(Y=>Y.card.dataSource),j=s.useEditorStore(Y=>Y.actions.setCardSql),x=s.useEditorStore(Y=>Y.actions.setRunSql),y=s.useEditorStore(Y=>Y.showAIDialog),g=s.useDashboardStore(Y=>Y.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:k}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:T}=s.useAssistantProfile(),{messages:w,setMessages:v,reload:D,append:b,input:A,setInput:S,isLoading:O,handleInputChange:M,handleSubmit:E,stop:N,chatStatus:L,llmUsage:B,errorMessage:P}=ei();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:w}),I.useEffect(()=>{var Y;y&&((Y=a.current)==null||Y.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[y,f,h]);function V(Y,Q){Q==="sql"?(j(Y),x(!0)):Q==="python"&&(k(Y),x(!0))}function q(){var Y;(Y=p==null?void 0:p.selectedEntities)==null||Y[0],m(!0)}function X(){u.selectedEntities.length===0&&h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function K(Y){X();const Q={role:"user",content:Y.title+" "+Y.subtitle};b(Q)}function $(Y){X(),b({role:"user",content:Y})}function F(){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 U(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const _=(A==null?void 0:A.length)===0&&(w==null?void 0:w.filter(Y=>Y.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:[U(),g&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:g,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[F(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:q,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{v([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{C(!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:w,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:w,chatStatus:L,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[_&&!T&&e.jsx(s.Placeholders,{onClick:K,placeholders:si}),e.jsx("div",{children:_&&T&&e.jsx(s.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:$})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:S,stop:N,input:A,handleInputChange:M,handleSubmit:Y=>{X(),E(Y)},isLoading:O,onFocus:()=>{}}),B&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.promptTokens," prompt tokens,"," ",B.completionTokens," completion tokens,"," ",B.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:d,onOpenChange:m,dataSource:f||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}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 ti(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 Is(){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 Ms(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Zs=t=>{var S;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:l,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),u=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,p=I.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=I.useCallback((O,M)=>{if(h)switch(O){case"groupBy":{a(h,{groupByColumns:M});break}case"metrics":{a(h,{metricColumns:M});break}case"pivotBy":{a(h,{pivotByColumns:M});break}case"sortBy":{a(h,{sortByColumns:M});break}}},[h,a]),j=I.useCallback((O,M,E)=>{if(!h)return;const L=p(O)[M];if(L)switch(O){case"groupBy":n(h,L.id,{label:E});break;case"metrics":r(h,L.id,{label:E});break;case"pivotBy":o(h,L.id,{label:E});break;case"sortBy":i(h,L.id,{label:E});break}},[h,p,n,r,o,i]),x=I.useCallback((O,M)=>{if(!h)return;const N=p("metrics")[O];N&&r(h,N.id,{aggregate:M,label:s.getAggregationLabel(N.name,M)})},[h,p,r]),y=I.useCallback((O,M,E)=>{if(!h)return;const L=p("groupBy")[O];if(!L)return;const B={dateFormat:M};M==="custom"&&E?B.customFormat=E:B.customFormat=void 0,n(h,L.id,B)},[h,p,n]),g=I.useCallback((O,M)=>{if(!h)return;const N=p("groupBy")[O];N&&n(h,N.id,{granularity:M})},[h,p,n]),C=I.useCallback((O,M)=>{if(!h)return;const N=p("metrics")[O];N&&r(h,N.id,{aliasTemplate:M})},[h,p,r]),k=I.useCallback((O,M)=>{if(console.log("handleValueAliasesChange",O,M),!h)return;console.log("handleValueAliasesChange",O,M);const N=p("metrics")[O];N&&(console.log("handleValueAliasesChange",M),r(h,N.id,{valueAliases:M}))},[h,p,r]),R=I.useCallback(O=>{h&&a(h,{comparisonType:O})},[h,a]),T=I.useCallback(O=>{h&&a(h,{showTrendline:O})},[h,a]),w=I.useCallback(O=>{h&&a(h,{trendlineWindow:O})},[h,a]),v=I.useCallback(O=>{h&&a(h,{trendlineGranularity:O})},[h,a]),D=I.useCallback(O=>{h&&a(h,{targetValue:O})},[h,a]),b=I.useCallback(O=>{var V;if(!h)return;const M=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],E=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,N=ti(O,M,E);if(!N.isValid){N.showError&&Is();return}const L=s.getSmartContainerForField(O),B=p(L);if(Ms(O,B))return;const P=s.getNewField(O,L);P&&f(L,[...B,P])},[h,(S=t==null?void 0:t.config)==null?void 0:S.joinPlan,p,f]),A=I.useCallback((O,M)=>{if(!h)return;const N=p(O)[M];if(N){if(O!=="sortBy"){const L=p("sortBy"),B=L.filter(P=>!(P.name===N.name&&P.qualifiedEntityName===N.qualifiedEntityName));B.length!==L.length&&a(h,{sortByColumns:B})}switch(O){case"groupBy":c(h,N.id);break;case"metrics":l(h,N.id);break;case"pivotBy":d(h,N.id);break;case"sortBy":m(h,N.id);break}}},[h,p,c,l,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:k,removeField:A,handleFieldClick:b,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:T,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:D,cardType:u}};function ni({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function ai({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=s.useSortable({id:t.id}),[l,d]=I.useState(!1),m=s.useEditorStore(j=>j.card),{handleFieldClick:u}=Zs(m),h={transform:s.CSS.Transform.toString(o),transition:i};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return Ye;case"date":return s.Calendar;case"boolean":return ts;case"json":return it;case"geo":return lt;default:return Qe}},f=j=>{const x=(j||"").toLowerCase(),y=s.getDataType(x);return y==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):y==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):y==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):y==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ts,{className:"h-3 w-3"})}):y==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(it,{className:"h-3 w-3"})}):y==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(lt,{className:"h-3 w-3"})}):y==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Dt,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>u(t),children:[f(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${l?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ni,{field:t})})]})})]}),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(Lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{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]=I.useState(""),[n,r]=I.useState("all"),o=s.useEditorStore(k=>k.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:l,error:d}=s.useColumns(),m=i.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),u=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const R=s.getDataType(k.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(k=>u(k)===n)).reduce((k,R)=>{const T=R.qualifiedEntityName||"Other Fields";return k[T]||(k[T]={label:s.toLabel(R.entityName),fields:[]}),k[T].fields.push(R),k},{}),j=Object.keys(p),x=m.filter(k=>u(k)==="dimensions").length,y=m.filter(k=>u(k)==="metrics").length,g=m.filter(k=>u(k)==="calculated").length,C=m.length>0;return l?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!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.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>a(k.target.value)})]}),C&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children: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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Dt,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(p).map(([k,R])=>{const T=c.find(w=>w.entityName===k)||{entityName:k,label:R.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children: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(w=>e.jsx(ai,{field:w},w.id))})})]},k)})}),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]=I.useState(t),[o,i]=I.useState(new Set),c=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,v]}),i(new Set([...o,v.id]))},l=w=>{r({...n,joins:n.joins.filter(v=>v.id!==w)}),i(new Set([...o].filter(v=>v!==w)))},d=(w,v)=>{var S,O;const D=n.joins.find(M=>M.id===w);if(!D)return;const b={...D,...v},A=n.joins.map(M=>M.id===w?b:M);if((S=b.source)!=null&&S.name&&((O=b.target)!=null&&O.name)&&b.joinKeyGroups[0].keys.length===0){const M=a.find(B=>{var P;return B.name===((P=b.source)==null?void 0:P.name)}),E=a.find(B=>{var P;return B.name===((P=b.target)==null?void 0:P.name)}),N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="},L=[...b.joinKeyGroups];L[0]={...L[0],keys:[N]},b.joinKeyGroups=L,A[A.findIndex(B=>B.id===w)]=b}r({...n,joins:A})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:l,updateJoin:d,moveJoinUp:w=>{const v=n.joins.findIndex(D=>D.id===w);if(v>0){const D=[...n.joins],b={...D[v]},A={...D[v-1]};D[v]=A,D[v-1]=b,D.forEach((O,M)=>{O.sequence=M+1});const S={...n,joins:D};r(S)}},moveJoinDown:w=>{const v=n.joins.findIndex(D=>D.id===w);if(v<n.joins.length-1){const D=[...n.joins],b={...D[v]},A={...D[v+1]};D[v]=A,D[v+1]=b,D.forEach((O,M)=>{O.sequence=M+1});const S={...n,joins:D};r(S)}},toggleJoinExpansion:w=>{const v=new Set(o);v.has(w)?v.delete(w):v.add(w),i(v)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const v=n.joins.findIndex(b=>b.id===w);if(v===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,v).forEach(b=>{D.add(b.source.name),D.add(b.target.name)}),a.filter(b=>D.has(b.name))},getAvailableTargetEntities:w=>a.filter(v=>v.name!==w),addJoinKeyGroup:w=>{const v=n.joins.find(b=>b.id===w);if(!v)return;const D=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(w,{joinKeyGroups:D})},updateGroupOperator:(w,v,D)=>{const b=n.joins.find(S=>S.id===w);if(!b)return;const A=[...b.joinKeyGroups];A[v]={...A[v],operator:D},d(w,{joinKeyGroups:A})},removeJoinKeyGroup:(w,v)=>{const D=n.joins.find(A=>A.id===w);if(!D)return;const b=[...D.joinKeyGroups];b.splice(v,1),d(w,{joinKeyGroups:b})},addJoinKey:(w,v)=>{const D=n.joins.find(M=>M.id===w);if(!D)return;const b=a.find(M=>M.name===D.source.name),A=a.find(M=>M.name===D.target.name),S=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(b==null?void 0:b.name)||"",entityName:(b==null?void 0:b.name)||"",entityType:(b==null?void 0:b.type)||"table"},target:{id:`target-${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"},operator:"="};S[v]={...S[v],keys:[...S[v].keys,O]},d(w,{joinKeyGroups:S})},updateJoinKey:(w,v,D,b,A)=>{const S=n.joins.find(L=>L.id===w);if(!S)return;const O=a.find(L=>L.name===S.source.name),M=a.find(L=>L.name===S.target.name),E=[...S.joinKeyGroups],N=E[v].keys[D];b==="sourceColumnName"&&O?E[v].keys[D]={...N,source:{...N.source,name:A}}:b==="targetColumnName"&&M?E[v].keys[D]={...N,target:{...N.target,name:A}}:b==="operator"&&(E[v].keys[D]={...N,operator:A}),d(w,{joinKeyGroups:E})},removeJoinKey:(w,v,D)=>{const b=n.joins.find(S=>S.id===w);if(!b)return;const A=[...b.joinKeyGroups];A[v].keys.splice(D,1),d(w,{joinKeyGroups:A})},generateSQLPreview:()=>{const w=[...n.joins].sort((b,A)=>b.sequence-A.sequence),v=n.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
430
|
+
FROM ${v.name}`;return w.forEach(b=>{const A=a.find(M=>M.name===b.target.name);if(!A)return;const S=b.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const E=M.keys.filter(N=>{var L,B,P,V;return((L=N.source)==null?void 0:L.name)&&((B=N.target)==null?void 0:B.name)&&((P=N.source)==null?void 0:P.entityName)&&((V=N.target)==null?void 0:V.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return E.length>1?`(${E.join(` ${M.operator} `)})`:E[0]}).filter(Boolean),O=S.length>1?S.join(" OR "):S[0]||"condition_here";D+=`
|
|
431
431
|
${b.joinType} JOIN ${A.name}
|
|
432
|
-
ON ${R}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(b=>!b.source.name||!b.target.name)||n.joins.some(b=>b.joinKeyGroups.some(A=>A.keys.length===0))||n.joins.some(b=>b.joinKeyGroups.some(A=>A.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function li({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:l,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:p,moveJoinUp:f,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:C,updateGroupOperator:k,removeJoinKeyGroup:O,addJoinKey:E,updateJoinKey:w,removeJoinKey:y,generateSQLPreview:D,isValidConfiguration:b}=ii({initialJoinPlan:t,availableDataSources:a}),A=S=>{const R=c.find(M=>M.entityName===S);return(R==null?void 0:R.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:S=>{const R=a.find(M=>M.name===S);m({...l,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:S,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),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(S=>{const R=a.find(N=>N.name===S.source.name),M=a.find(N=>N.name===S.target.name),T=d.has(S.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:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,R&&M&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",M.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(S.id),disabled:S.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:T?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),T&&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:S.source.name,onValueChange:N=>{const L=a.find(B=>B.name===N);p(S.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:N,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(S.id).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name]})},N.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:N=>p(S.id,{joinType:N}),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:S.target.name,onValueChange:N=>{const L=a.find(B=>B.name===N);p(S.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:N,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?j(S.source.name).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,N.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},N.name)):[]})]})]})]}),S.source.name&&S.target.name&&R&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.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:S.joinKeyGroups.map((N,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:N.operator,onValueChange:B=>k(S.id,L,B),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(S.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[N.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:N.keys.map((B,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:N.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.source.name,onValueChange:V=>w(S.id,L,P,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:A(S.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:B.operator,onValueChange:V=>w(S.id,L,P,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.target.name,onValueChange:V=>w(S.id,L,P,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:A(S.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(S.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},B.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(S.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},N.id))})]})]})]},S.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:!b(),children:"Save"})]})]})}function vt({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,m)=>d+m.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,m)=>d+m.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 u,h;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=I.useState(!1),i=((h=t==null?void 0:t.dataSource)==null?void 0:h.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)},m=()=>{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 *
|
|
433
|
-
FROM ${f.name}`;return p.forEach(x=>{const
|
|
434
|
-
${x.joinType} JOIN ${
|
|
435
|
-
ON ${C}`}),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:m})})]})}),e.jsx(vt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(vt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ui({open:t,onOpenChange:a}){const[n,r]=I.useState([]),{updateDataSource:o}=s.useEditorActions(),i=s.useDashboardStore(x=>x.dashboard.aiContext),c=(i==null?void 0:i.selectedEntities)||[];I.useEffect(()=>{t&&r([])},[t]);const l=x=>{r(v=>v.some(C=>C.name===x.name&&C.type===x.type)?v.filter(C=>!(C.name===x.name&&C.type===x.type)):[...v,x])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(n.length===0)return;const x=n[0],v=x.connectionId||"",j=x.connectionType||"",k=n.some(E=>E.type==="dataset")?"semanticDomain":"database";o({connectionId:v,connectionType:j,mode:k,selectedEntities:n}),a(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ma,{className:"h-4 w-4"});case"model":return e.jsx(sa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},p=x=>"label"in x&&x.label?x.label:x.name,f=x=>{if("description"in x&&x.description)return x.description;const v=[];return x.database&&v.push(x.database),x.schema&&v.push(x.schema),x.name&&v.push(x.name),v.join(".")},g=x=>n.some(v=>v.name===x.name&&v.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data from AI Context"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's AI context to use as your data source."})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,v)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",g(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:g(x),onCheckedChange:()=>l(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${v}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function mi({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 hi({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 xi({isVisible:t,onToggleVisibility:a}){s.useEditorStore(p=>p.isDevMode),s.useEditorStore(p=>p.card.connectionId),s.useDashboardStore(p=>p.isVisualEditing);const[n,r]=I.useState(!1),[o,i]=I.useState(!1),[c,l]=I.useState(!0),d=s.useEditorStore(p=>p.card.dataSource),{updateDataSource:m}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...u,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick: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(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Select"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((p,f)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(p),e.jsx("button",{onClick:g=>{g.stopPropagation();const x=h.selectedEntities.filter(v=>!(v.name===p.name&&v.type===p.type));m({...u,...d,selectedEntities:x})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(mi,{entity:p})]},`${p.type}-${p.name}-${f}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(hi,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(di,{})]})]}),e.jsx(oi,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:u}),e.jsx(ui,{open:o,onOpenChange:i})]})}const ss=[{id:"table",icon:He,label:"Table"},{id:"pivotTable",icon:He,label:"Pivot Table"},{id:"bar",icon:cs,label:"Bar Chart"},{id:"line",icon:ds,label:"Line Chart"},{id:"area",icon:kt,label:"Area Chart"},{id:"stackedBar",icon:As,label:"Stacked Bar Chart"},{id:"combo",icon:Wn,label:"Combo Chart"},{id:"stackedLine",icon:Ks,label:"Stacked Line Chart"},{id:"scatter",icon:Rs,label:"Scatter Chart"},{id:"bubble",icon:Hs,label:"Bubble Chart"},{id:"pie",icon:us,label:"Pie Chart"},{id:"doughnut",icon:Os,label:"Doughnut Chart"},{id:"funnel",icon:Qs,label:"Funnel Chart"},{id:"radar",icon:Bs,label:"Radar Chart"},{id:"polarArea",icon:Gs,label:"Polar Area Chart"},{id:"tornado",icon:zs,label:"Tornado Chart"},{id:"range",icon:Ls,label:"Range Chart"},{id:"kpi",icon:Ws,label:"KPI"},{id:"text",icon:wt,label:"Text"},{id:"map",icon:Fs,label:"Map"}],et=t=>{const a=t.toLowerCase();for(const n of ss)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return I.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return I.createElement(r,{className:"h-4 w-4"})}return null},pi="chart-selector-standard-first";function fi(){const[t,a]=s.useLocalStorageState(pi,!0);return{standardFirst:t,updatePreference:a}}const bt=({pluginVisual:t,index:a,onSelect:n})=>{const r=hs(t.icon||""),o=t.name.charAt(0).toUpperCase(),i=et(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}`)},Nt=["default","standardPlugin","customPlugin"];function gi({selectedChart:t,onChartChange:a}){var w;const[n,r]=I.useState([]),[o,i]=I.useState(!1),{data:c}=Ys();fi();const d=((w=s.useEditorStore(y=>y.card).customCardPreferences)==null?void 0:w.url)||"";Ps(d);const{setCardType:m,setCardPreferences:u,setIsDevMode:h}=s.useEditorStore(y=>y.actions),{setCardCustomCfg:p,setCustomCardPreferences:f,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=I.useMemo(()=>x?[x,...Nt.filter(y=>y!==x)]:Nt,[x]);I.useEffect(()=>{(async()=>{if(c){const b=(await Promise.allSettled(c.plugins.map(async A=>{try{return(await s.loadManifest(A.value)).visuals.map(R=>({name:R.name,icon:R.icon,url:A.value,pluginName:A.label,pluginType:A.type,chartType:R.chartType,componentType:R.componentType}))}catch(S){return console.error(`Failed to load manifest for plugin ${A.label}`,S),[]}}))).filter(A=>A.status==="fulfilled").flatMap(A=>A.value);r(b)}})()},[c]);function C(y){p(null),u({}),m(y),["custom","text","map"].includes(y)&&(h(!0),g(void 0)),a(y),i(!1)}function k(y){p(null),u({}),m("custom"),f({type:"component",visualType:"single",url:y.url,componentName:y.name,icon:y.icon,pluginChartType:y.chartType}),g(void 0),a("custom"),i(!1)}const O=()=>{var D;if(t==="custom"){const b=s.useEditorStore.getState().card;return((D=b==null?void 0:b.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const y=ss.find(b=>b.id===t);return(y==null?void 0:y.label)||"Select chart type"},E=()=>{var D,b;if(t==="custom"){const A=s.useEditorStore.getState().card,S=(D=A==null?void 0:A.customCardPreferences)==null?void 0:D.icon,R=(b=A==null?void 0:A.customCardPreferences)==null?void 0:b.componentName;if(S&&R)return e.jsx(ji,{icon:S,componentName:R});if(R){const M=et(R);if(M)return M}return e.jsx(Ye,{className:"h-4 w-4"})}const y=ss.find(A=>A.id===t);if(y){const A=y.icon;return e.jsx(A,{className:"h-4 w-4"})}return e.jsx(Ye,{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:[E(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(y=>{if(y==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:D=>v(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ss.map(D=>{const b=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>C(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(y==="standardPlugin"){const D=n.filter(b=>b.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:b=>v(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(b=>b.componentType==="chart").map((b,A)=>e.jsx(bt,{pluginVisual:b,index:A,onSelect:()=>k(b)},`${b.url}-${b.name}-${A}`))},"standardPlugin"):null}if(y==="customPlugin"){const D=n.filter(b=>b.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:b=>v(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((b,A)=>e.jsx(bt,{pluginVisual:b,index:A,onSelect:()=>k(b)},`${b.url}-${b.name}-${A}`))},"customPlugin"):null}return null})]})]})})]})})}const ji=({icon:t,componentName:a})=>{const n=hs(),r=et(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ye,{className:"h-4 w-4"})},Sn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx($e,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ts,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})})};function yi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=I.useState(t),[o,i]=I.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&o&&n!==t?(a(n),i(!1)):m.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 vi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=I.useState(null),[o,i]=I.useState(""),[c,l]=I.useState(""),d=()=>{a({...t,"":""})},m=h=>{const p={...t};delete p[h],a(p)},u=h=>{const p={...t};delete p[h],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(([h,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?u(h):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"?u(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),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(h),i(h),l(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+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 Ct({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=I.useState(t??""),[l,d]=I.useState(!1);I.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(i),d(!1)},u=()=>{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:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&l&&i!==t?m():h.key==="Escape"&&u()},"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:m,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function bi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var nt;const{attributes:l,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(W=>W.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:C,handleValueAliasesChange:k,removeField:O,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:b}=Zs(f),[A,S]=I.useState(!1),[R,M]=I.useState(t.dateFormat||"YYYY-MM-DD"),[T,N]=I.useState(t.customFormat||""),[L,B]=I.useState(!!t.customFormat),[P,V]=I.useState(t.granularity||"day"),[U,X]=I.useState(t.aliasTemplate||""),[K,F]=I.useState(t.valueAliases||{}),_=W=>{W==="custom"?B(!0):(B(!1),M(W),a==="groupBy"&&v(n,W,""))},$=W=>{N(W),a==="groupBy"&&v(n,"custom",W)},q=W=>{var Ue;V(W);const xe=(Ue=H(W)[0])==null?void 0:Ue.value;xe&&!L&&(M(xe),a==="groupBy"&&v(n,xe,"")),a==="groupBy"&&j(n,W)},Y=W=>{X(W),a==="metrics"&&C(n,W)},Q=W=>{F(W),a==="metrics"&&k(n,W)},G=W=>{g(a,n,W)},Z=()=>{O(a,n)},te={transform:s.CSS.Transform.toString(u),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},z=H(P),J=!oe&&a!=="pivotBy",ie=se&&a==="groupBy",be=!oe&&se&&a==="groupBy",ke=oe&&se&&a==="groupBy",ne=oe&&a==="metrics"&&((nt=f.config)==null?void 0:nt.comparisonType)==="target",le=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:W=>{W.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),kn=()=>J?e.jsx(Ct,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,tt=()=>ie?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:P,onValueChange:q,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,En=()=>be?e.jsxs(e.Fragment,{children:[tt(),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:L?"custom":R,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:z.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),L&&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:T,onChange:W=>{W.stopPropagation(),$(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Tn=()=>{var W,ge,xe,Ue,at;return ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=f.config)==null?void 0:W.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ge=f.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:w})]})}),((xe=f.config)==null?void 0:xe.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((Ue=f.config)==null?void 0:Ue.trendlineWindow)||30,onChange:An=>{const Ln=parseInt(An.target.value)||30;y(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:((at=f.config)==null?void 0:at.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},In=()=>{var W,ge;return ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Ct,{value:((W=f.config)==null?void 0:W.targetValue)!==void 0&&((ge=f.config)==null?void 0:ge.targetValue)!==null?String(f.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?b(Number(xe)):b(0)},placeholder:"Enter target value...",type:"text"})]}):null},Mn=()=>le?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{x(n,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(bn,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(yi,{aliasTemplate:U,onAliasTemplateChange:Y}),e.jsx(vi,{valueAliases:K,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:m,style:te,...l,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Sn,{dataType:ae}),e.jsx(Js,{className:"w-[140px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),o(ge)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[ce(),kn(),c==="kpi"&&tt(),En(),Tn(),In(),Mn()]})]})}function Ni({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 Ze({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(),m=s.useEditorStore(g=>g.card),u=s.useEditorStore(g=>g.card.type),h=a.length>0,p=(g,x)=>{var j;!((j=m.config)!=null&&j.sortByColumns)||m.config.sortByColumns.findIndex(C=>C.id===g)===-1||d(m.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Ni,{concept:t})]}),e.jsx("div",{ref:l,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(bi,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:C=>p(g.id,C),hasPivotColumns:i,cardType:u})})},g.id)})})})})]})}function Ci({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),i=o==null?void 0:o.type,c=t.length>0||n.length>0,l=i!=="kpi",d=i!=="kpi"&&c,m=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},u=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"w-full space-y-4",children:[e.jsx(Ze,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),l&&e.jsx(Ze,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:n,label:u().label,placeholder:u().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Ze,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Si({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=s.useEditorStore(h=>h.showAIDialog),l=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(gi,{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||u}),children:e.jsx(ms,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ea,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6",children:[e.jsx(Ci,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function wi({initialFilters:t,availableFields:a}={}){const[n,r]=I.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.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"},m=E=>{const w=y=>{if(y.id===E){const D=l[0]||d;return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...y,groups:y.groups.map(w)}};r(w(n))},u=E=>{const w=y=>{if(y.id===E){const D=l[0]||d;return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...y,groups:y.groups.map(w)}};r(w(n))},h=(E,w)=>{const y=D=>D.id===E?{...D,conditions:D.conditions.filter(b=>b.id!==w)}:{...D,groups:D.groups.map(y)};r(y(n))},p=(E,w)=>{const y=D=>D.id===E?{...D,groups:D.groups.filter(b=>b.id!==w)}:{...D,groups:D.groups.map(y)};r(y(n))},f=(E,w,y,D)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const b=A=>A.id===E?{...A,conditions:A.conditions.map(S=>S.id===w?{...S,[y]:D}:S)}:{...A,groups:A.groups.map(b)};r(b(n))},g=(E,w,y)=>{const D=b=>b.id===E?{...b,conditions:b.conditions.map(A=>A.id===w?{...A,...y}:A)}:{...b,groups:b.groups.map(D)};r(D(n))},x=(E,w)=>{const y=D=>D.id===E?{...D,logicalOperator:w}:{...D,groups:D.groups.map(y)};r(y(n))},v=(E,w)=>{const y=D=>D.id===E?{...D,negate:w}:{...D,groups:D.groups.map(y)};r(y(n))},j=(E,w,y)=>{const D=b=>b.id===E?{...b,conditions:s.arrayMove(b.conditions,w,y)}:{...b,groups:b.groups.map(D)};r(D(n))},C=(E,w,y)=>{const D=b=>b.id===E?{...b,groups:s.arrayMove(b.groups,w,y)}:{...b,groups:b.groups.map(D)};r(D(n))},k=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const w=D=>{let b="";typeof D.field=="object"?b=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:b=String(D.field);const A=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date")(typeof S=="string"||S instanceof Date)&&(S=`DATE('${S}')`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(S)?R=S.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof S=="string"?R=S.split(",").map(M=>{const T=M.trim();return D.field.dataType==="string"?`'${T}'`:T}):typeof S=="number"&&(R=[String(S)]),S=`(${R.join(", ")})`}switch(A){case"contains":return typeof S=="string"?`${b} LIKE '%${S.replace(/'/g,"")}'`:`${b} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${b} LIKE '${S.replace(/'/g,"")}%'`:`${b} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${b} LIKE '%${S.replace(/'/g,"")}'`:`${b} LIKE '%${String(S)}'`;default:return`${b} ${A} ${S}`}},y=D=>{const b=D.conditions.map(w),A=D.groups.map(T=>y(T)),S=[...b,...A].filter(Boolean);if(S.length===0)return"";const R=S.join(` ${D.logicalOperator} `),M=S.length>1?`(${R})`:R;return D.negate?`NOT ${M}`:M};return y(E)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:m,addGroup:u,removeCondition:h,removeGroup:p,updateCondition:f,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:C,generateSQLPreview:k,hasAnyFilters:O}}function Di({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 ki=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(oa,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Ei=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]=I.useState(!1),l=I.useMemo(()=>{const d={};return n.forEach(m=>{const u=Ei(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][m.entityId].push(m)}),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(Di,{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,m])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(m).map(([u,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[ki(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.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}-${u}`))},d))})]})})]})}function st(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]},m=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:u,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function Ii({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=ue.useState(!1),{filterValues:l}=st(t),d=u=>{n(a.filter(h=>h!==u))},m=u=>{a.includes(u)?n(a.filter(h=>h!==u)):n([...a,u])};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(u=>{const h=l.find(p=>p.value===u);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(u)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:l.map((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const wn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=wn(n)}),a};function Mi({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:l}=st(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,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Ai=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Li=["=","!=","contains","startsWith","endsWith","in","not in"],Ri=["=","!=",">",">=","<","<=","in","not in"],Oi=["=","!="],Fi=["=","!=",">",">=","<","<=","in","not in"];function Bi(t){switch(t){case"string":return Li;case"number":return Ri;case"boolean":return Oi;case"date":return Fi;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:m,listeners:u,setNodeRef:h,transform:p,transition:f,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=st(t.field),j={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...u,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:C=>c(n,C),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:C=>{d(n,t.id,{field:C,value:""})},availableFields:l,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?d(n,t.id,{operator:C,value:[]}):d(n,t.id,{operator:C,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(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:C},C))})]}),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(Ii,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Mi,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C==="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:C=>o(n,t.id,"value",C.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 zi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:p,availableFields:f,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:C,transform:k,transition:O,isDragging:E}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(k),transition:O},y=b=>{const{active:A,over:S}=b;if(S&&A.id!==S.id){const R=t.conditions.findIndex(T=>T.id===A.id),M=t.conditions.findIndex(T=>T.id===S.id);R!==-1&&M!==-1&&m(t.id,R,M)}},D=b=>{const{active:A,over:S}=b;if(S&&A.id!==S.id&&n){const R=t.groups.findIndex(T=>T.id===A.id),M=t.groups.findIndex(T=>T.id===S.id);R!==-1&&M!==-1&&u(n,R,M)}};return e.jsxs("div",{ref:C,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:b=>r(t.id,b),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:y,children:e.jsx(s.SortableContext,{items:t.conditions.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((b,A)=>e.jsx(Dn,{condition:b,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},b.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(b=>g(b,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>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:m,removeCondition:u,removeGroup:h,updateCondition:p,updateConditionFields:f,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:C,hasAnyFilters:k,setCurrentFilters:O}=wi({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,y]=I.useState(!1),D=(S,R,M)=>{const T=N=>N.id===S?{...N,conditions:N.conditions.map(L=>L.id===R?{...L,field:M,dataType:M.dataType}:L)}:{...N,groups:N.groups.map(T)};O(T(i))},b=(S,R=0,M)=>R===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:N,over:L}=T;if(L&&N.id!==L.id){const B=S.conditions.findIndex(V=>V.id===N.id),P=S.conditions.findIndex(V=>V.id===L.id);B!==-1&&P!==-1&&v(S.id,B,P)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((T,N)=>e.jsx(Dn,{condition:T,index:N,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:u,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:N,over:L}=T;if(L&&N.id!==L.id){const B=S.groups.findIndex(V=>V.id===N.id),P=S.groups.findIndex(V=>V.id===L.id);B!==-1&&P!==-1&&j(S.id,B,P)}},children:e.jsx(s.SortableContext,{items:S.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(T=>b(T,R+1,S.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(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(zi,{group:S,depth:R,parentGroupId:M,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:u,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:b,updateConditionFields:f},S.id),A=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..."})]}):b(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:w,onCheckedChange:S=>y(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(k?i:null),children:"Apply Filters"})]})]})}function Vi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const l=m=>{n(t,m),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:m=>{m.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(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]=I.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")],m=I.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]),u=I.useCallback(g=>{i(g.active.id)},[]),h=I.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){i(null);return}const j=x.id,C=v.id,k=m(j),O=m(C)||C;if(k==="source"&&O==="sortBy"){i(null);return}if(k==="source"&&O!=="source"&&O!=="sortBy"){const E=[...a].find(b=>b.id===j);if(!E){i(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const b=w[0].qualifiedEntityName;if(!b){i(null);return}if(b!==E.qualifiedEntityName&&E.qualifiedEntityName)if(l){if(!Cn(b,E.qualifiedEntityName,l)){Is(),i(null);return}}else{Is(),i(null);return}}const y=n(O);if(Ms(E,y)){i(null);return}const D=s.getNewField(E,O);i(null),r(O,[...y,D]);return}if(k&&O&&k!=="source"&&O!=="source"&&k!==O){const E=n(k),w=n(O),y=E.find(A=>A.id===j);if(!y){i(null);return}const D=s.getNewField(y,O);if(i(null),O==="sortBy"){if(k==="pivotBy"){i(null);return}Ms(y,w)||r(O,[...w,D]);return}const b=E.filter(A=>A.id!==j);r(k,b),r(O,[...w,D]);return}if(k&&O&&k===O&&k!=="source"){const E=n(k),w=E.findIndex(D=>D.id===j),y=E.findIndex(D=>D.id===C);if(w!==y){const D=s.arrayMove(E,w,y);r(k,D)}}i(null)},[t,a,n,r,m,l]),p=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:p,handleDragStart:u,handleDragEnd:h}}function Ui({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}=I.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showAdvancedMode)!==!1,{setIsDevMode:l}=s.useEditorActions(),d=s.useEditorStore(f=>f.showAIDialog),m=s.useEditorStore(f=>f.frame),u=s.useManagementStore(f=>f.selectedVisual),h=(u==null?void 0:u.id)===(m==null?void 0:m.id),{setShowAIDialog:p}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>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&&!h&&e.jsx(qs,{variant:"default"}),h&&e.jsx(Wr,{}),a&&s.isDevEnv]})]})}function qi({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 Yi(){var d,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=I.useState(!1),[o,i]=I.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(t.id,parseInt(u))},l=u=>{const h=u.target.value;i(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:$i.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function Gi({isOpen:t,onClose:a}){const n=Gt(a,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(u=>u.card),i=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:l}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),m=I.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:m&&e.jsx(I.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{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:m,columns:u,columnsLoading:h,columnsError:p}){var L;const f=s.useEditorStore(B=>B.card);s.useEditorStore(B=>B.frame);const g=s.useDashboardStore(B=>B.filterValues),{updateCardConfig:x,setCard:v,updateCardInFrame:j}=s.useEditorActions(),C=s.useEditorStore(B=>B.showAIDialog),[k,O]=I.useState(!1),E=s.useEditorStore(B=>{var P;return((P=B.card.customCardPreferences)==null?void 0:P.url)&&B.card.type==="custom"}),{data:w,errorMessage:y,isPending:D,isLoading:b,isFetching:A,pagination:S}=s.useDashboardCardQuery(m),R=(B,P)=>{const V={...m,paginationConfig:{page:B+1,pageSize:P}};v(V),j(V)};function M(){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(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const T=B=>{if(!f.config)return;if(!B.length){x(f.id,{...f.config,sortByColumns:[]});return}const P=f.config,V=B.map(({id:U,desc:X})=>{var $,q;const K=($=P.metricColumns)==null?void 0:$.find(Y=>Y.label===U),F=(q=P.groupByColumns)==null?void 0:q.find(Y=>Y.label===U),_=K||F;return _?{id:s.getFieldId("sortBy",_),name:_.name,dataType:_.dataType,label:_.label,qualifiedEntityName:_.qualifiedEntityName,entityId:_.entityId,entityName:_.entityName,entityType:_.entityType,role:"sortby",direction:X?"desc":"asc"}:null}).filter(U=>U!==null);x(f.id,{...P,sortByColumns:V})},N=I.useMemo(()=>{var B,P;return(P=(B=f.config)==null?void 0:B.sortByColumns)==null?void 0:P.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(L=f.config)==null?void 0:L.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Ui,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d}),n&&M(),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"&&C&&e.jsx(hn,{variant:"outline"}),e.jsx(qi,{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(Yi,{})}),C&&e.jsx(ms,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(xn,{})})]}),!k&&E&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>O(!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(wa,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(pn,{})}),t==="table"&&(w==null?void 0:w.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(w==null?void 0:w.records)||[],paginationMetadata:S,onPaginationChange:R,isLoading:b||A,onSortChange:T,sortState:N})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(w==null?void 0:w.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(rn,{sql:w==null?void 0:w.sql,error:y})]})})]}),e.jsx(Gi,{isOpen:k,onClose:()=>O(!1)})]})]})}function Qi({activeField:t}){const[a,n]=I.useState(!0);return I.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 Ki=()=>{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 F,_;const[t,a]=I.useState("chart"),[n,r]=I.useState(!1),[o,i]=I.useState(!1),[c,l]=I.useState(!0),d=s.useEditorStore($=>$.showAIDialog),m=s.useDashboardStore($=>$.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore($=>$.card.type);I.useEffect(()=>Ki(),[]);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=$=>{u($)},j=s.useEditorStore($=>$.frame),C=s.useEditorStore($=>$.card);s.useEditorStore($=>$.activeTabCardId),s.useEditorStore($=>$.actions.getAvailableFields);const{addCard:k,removeCard:O,updateCard:E,setActiveCard:w,updateFilters:y}=s.useEditorActions(),{columns:D=[],isLoading:b,error:A}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=C,{getFieldsForContainer:M,setFieldsForContainer:T}=Zs(R),{activeField:N,handleDragStart:L,handleDragEnd:B}=_i({activeCardId:j.activeCardId,sourceFields:D,getFieldsForContainer:M,setFieldsForContainer:T}),P=($,q)=>{q&&y($,q)},V=$=>{var q;E($,{config:{...(q=j.cards.find(Y=>Y.id===$))==null?void 0:q.config,filters:void 0}})},U=D,X=$=>{if(!$)return 0;let q=$.conditions.length;return $.groups.forEach(Y=>{q+=X(Y)}),q},K=X(((F=R==null?void 0:R.config)==null?void 0:F.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:L,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(xi,{isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Si,{selectedChart:h,onChartChange:v,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy")}),e.jsx(Hi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:g,onFiltersClick:x,filterCount:K,activeCard:R,dataSourceState:C.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:b,columnsError:A,getFieldsForContainer:M,cards:j.cards,activeCardId:j.activeCardId,addCard:k,setActiveCard:w})]}),!c&&m&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),R&&e.jsx(Vi,{cardId:R.id,filters:((_=R.config)==null?void 0:_.filters)||null,onFiltersChange:P,onClearFilters:V,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Qi,{activeField:N||null})})]})}function Ji({authToken:t,onSave:a,onClose:n}){const r=I.useRef(null),o=s.useEditorStore(C=>C.showAIDialog),i=s.useEditorStore(C=>C.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:l,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:p,handleDragCancel:f,sensors:g}=Br();I.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),I.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),I.useEffect(()=>{var C,k;o?((C=r.current)==null||C.resize(40),l(!0)):(l(!1),(k=r.current)==null||k.resize(0))},[o,l]);function x(C){C<1?l(!1):o||l(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(nn,{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(yt,{})})]})]})}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(yt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx(s.DndContext,{sensors:g,onDragStart:p,onDragEnd:h,onDragOver:u,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Xi(){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 Zi(){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}=yn();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(_s,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function el(){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(nn,{type:"filter",ColumnsComponent:()=>e.jsx(Zi,{})})})]})}function sl(){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 tl(){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(sl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(el,{})})]})}function nl(){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 al({showControls:t=!1,showFooter:a=!0,...n}){return typeof window>"u"?null: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(nl,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Ar,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Xi,{}),e.jsx(tl,{})]})]})]})]})})}exports.DashboardPlus=al;exports.ResourceManagementPanel=sn;exports.ScheduleDashboard=Bt;exports.SelectComponent=Pe;exports.cleanCard=Rt;exports.downloadPdf=Ft;exports.getDashbaordStateWithoutData=ns;
|
|
432
|
+
ON ${O}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(b=>!b.source.name||!b.target.name)||n.joins.some(b=>b.joinKeyGroups.some(A=>A.keys.length===0))||n.joins.some(b=>b.joinKeyGroups.some(A=>A.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function li({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:l,expandedJoins:d,setJoinPlan:m,addJoin:u,removeJoin:h,updateJoin:p,moveJoinUp:f,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:y,getAvailableTargetEntities:g,addJoinKeyGroup:C,updateGroupOperator:k,removeJoinKeyGroup:R,addJoinKey:T,updateJoinKey:w,removeJoinKey:v,generateSQLPreview:D,isValidConfiguration:b}=ii({initialJoinPlan:t,availableDataSources:a}),A=S=>{const O=c.find(M=>M.entityName===S);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:S=>{const O=a.find(M=>M.name===S);m({...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:S,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(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",l.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),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(S=>{const O=a.find(N=>N.name===S.source.name),M=a.find(N=>N.name===S.target.name),E=d.has(S.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:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,O&&M&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",M.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(S.id),disabled:S.sequence===l.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:E?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),E&&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:S.source.name,onValueChange:N=>{const L=a.find(B=>B.name===N);p(S.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:N,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(S.id).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name]})},N.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:N=>p(S.id,{joinType:N}),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:S.target.name,onValueChange:N=>{const L=a.find(B=>B.name===N);p(S.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:N,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?g(S.source.name).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,N.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},N.name)):[]})]})]})]}),S.source.name&&S.target.name&&O&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.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:S.joinKeyGroups.map((N,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:N.operator,onValueChange:B=>k(S.id,L,B),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(S.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[N.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:N.keys.map((B,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:N.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.source.name,onValueChange:V=>w(S.id,L,P,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:A(S.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:B.operator,onValueChange:V=>w(S.id,L,P,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.target.name,onValueChange:V=>w(S.id,L,P,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:A(S.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(S.id,L,P),children:e.jsx(s.X,{className:"size-3.5"})})]},B.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(S.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},N.id))})]})]})]},S.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:!b(),children:"Save"})]})]})}function vt({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,m)=>d+m.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,m)=>d+m.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 u,h;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((u=t==null?void 0:t.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=I.useState(!1),i=((h=t==null?void 0:t.dataSource)==null?void 0:h.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)},m=()=>{const p=[...n.joins].sort((x,y)=>x.sequence-y.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
433
|
+
FROM ${f.name}`;return p.forEach(x=>{const y=i.find(k=>k.name===x.target.name);if(!y)return;const g=x.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const R=k.keys.filter(T=>{var w,v,D,b;return((w=T.source)==null?void 0:w.name)&&((v=T.target)==null?void 0:v.name)&&((D=T.source)==null?void 0:D.entityName)&&((b=T.target)==null?void 0:b.entityName)}).map(T=>`${T.source.entityName}.${T.source.name} ${T.operator} ${T.target.entityName}.${T.target.name}`);return R.length>1?`(${R.join(` ${k.operator} `)})`:R[0]}).filter(Boolean),C=g.length>1?g.join(" OR "):g[0]||"condition_here";j+=`
|
|
434
|
+
${x.joinType} JOIN ${y.name}
|
|
435
|
+
ON ${C}`}),j};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:m})})]})}),e.jsx(vt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(vt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:l,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ui({open:t,onOpenChange:a}){const[n,r]=I.useState([]),{updateDataSource:o}=s.useEditorActions(),i=s.useDashboardStore(x=>x.dashboard.aiContext),c=(i==null?void 0:i.selectedEntities)||[];I.useEffect(()=>{t&&r([])},[t]);const l=x=>{r(y=>y.some(C=>C.name===x.name&&C.type===x.type)?y.filter(C=>!(C.name===x.name&&C.type===x.type)):[...y,x])},d=()=>{r([...c])},m=()=>{r([])},u=()=>{if(n.length===0)return;const x=n[0],y=x.connectionId||"",g=x.connectionType||"",k=n.some(T=>T.type==="dataset")?"semanticDomain":"database";o({connectionId:y,connectionType:g,mode:k,selectedEntities:n}),a(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ma,{className:"h-4 w-4"});case"model":return e.jsx(sa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},p=x=>"label"in x&&x.label?x.label:x.name,f=x=>{if("description"in x&&x.description)return x.description;const y=[];return x.database&&y.push(x.database),x.schema&&y.push(x.schema),x.name&&y.push(x.name),y.join(".")},j=x=>n.some(y=>y.name===x.name&&y.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:m,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>l(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:f(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:u,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function mi({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 hi({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 xi({isVisible:t,onToggleVisibility:a}){s.useEditorStore(f=>f.isDevMode),s.useEditorStore(f=>f.card.connectionId),s.useDashboardStore(f=>f.isVisualEditing);const[n,r]=I.useState(!1),[o,i]=I.useState(!1),[c,l]=I.useState(!0),d=s.useEditorStore(f=>f.card.dataSource),{currentUser:m}=be(),{updateDataSource:u}=s.useEditorActions(),h={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},p={...h,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),(m==null?void 0:m.type)==="organization"&&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"]}),(m==null?void 0:m.type)==="tenant"&&e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Select"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[p.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[p.selectedEntities.slice(0,3).map((f,j)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:x=>{x.stopPropagation();const y=p.selectedEntities.filter(g=>!(g.name===f.name&&g.type===f.type));u({...h,...d,selectedEntities:y})},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(mi,{entity:f})]},`${f.type}-${f.name}-${j}`)),p.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:["+",p.selectedEntities.length-3," more"]})}),e.jsx(hi,{entities:p.selectedEntities.slice(3)})]})]})}),e.jsx(di,{})]})]}),e.jsx(oi,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:p,fallbackDataSource:h}),e.jsx(ui,{open:o,onOpenChange:i})]})}const ss=[{id:"table",icon:Ve,label:"Table"},{id:"pivotTable",icon:Ve,label:"Pivot Table"},{id:"aggregateTable",icon:Ve,label:"Aggregate Table"},{id:"bar",icon:cs,label:"Bar Chart"},{id:"line",icon:ds,label:"Line Chart"},{id:"area",icon:kt,label:"Area Chart"},{id:"stackedBar",icon:As,label:"Stacked Bar Chart"},{id:"combo",icon:Wn,label:"Combo Chart"},{id:"stackedLine",icon:Ks,label:"Stacked Line Chart"},{id:"scatter",icon:Os,label:"Scatter Chart"},{id:"bubble",icon:Hs,label:"Bubble Chart"},{id:"pie",icon:us,label:"Pie Chart"},{id:"doughnut",icon:Rs,label:"Doughnut Chart"},{id:"funnel",icon:Qs,label:"Funnel Chart"},{id:"radar",icon:Bs,label:"Radar Chart"},{id:"polarArea",icon:Gs,label:"Polar Area Chart"},{id:"tornado",icon:zs,label:"Tornado Chart"},{id:"range",icon:Ls,label:"Range Chart"},{id:"kpi",icon:Ws,label:"KPI"},{id:"text",icon:wt,label:"Text"},{id:"map",icon:Fs,label:"Map"}],et=t=>{const a=t.toLowerCase();for(const n of ss)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return I.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return I.createElement(r,{className:"h-4 w-4"})}return null},pi="chart-selector-standard-first";function fi(){const[t,a]=s.useLocalStorageState(pi,!0);return{standardFirst:t,updatePreference:a}}const bt=({pluginVisual:t,index:a,onSelect:n})=>{const r=hs(t.icon||""),o=t.name.charAt(0).toUpperCase(),i=et(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}`)},Nt=["default","standardPlugin","customPlugin"];function gi({selectedChart:t,onChartChange:a}){var w;const[n,r]=I.useState([]),[o,i]=I.useState(!1),{data:c}=Ys();fi();const d=((w=s.useEditorStore(v=>v.card).customCardPreferences)==null?void 0:w.url)||"";Ps(d);const{setCardType:m,setCardPreferences:u,setIsDevMode:h}=s.useEditorStore(v=>v.actions),{setCardCustomCfg:p,setCustomCardPreferences:f,setQueryConfig:j}=s.useEditorActions(),[x,y]=s.useLocalStorageState("chart-section-active",null),g=I.useMemo(()=>x?[x,...Nt.filter(v=>v!==x)]:Nt,[x]);I.useEffect(()=>{(async()=>{if(c){const b=(await Promise.allSettled(c.plugins.map(async A=>{try{return(await s.loadManifest(A.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:A.value,pluginName:A.label,pluginType:A.type,chartType:O.chartType,componentType:O.componentType}))}catch(S){return console.error(`Failed to load manifest for plugin ${A.label}`,S),[]}}))).filter(A=>A.status==="fulfilled").flatMap(A=>A.value);r(b)}})()},[c]);function C(v){p(null),u({}),m(v),["custom","text","map"].includes(v)&&(h(!0),j(void 0)),a(v),i(!1)}function k(v){p(null),u({}),m("custom"),f({type:"component",visualType:"single",url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType}),j(void 0),a("custom"),i(!1)}const R=()=>{var D;if(t==="custom"){const b=s.useEditorStore.getState().card;return((D=b==null?void 0:b.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const v=ss.find(b=>b.id===t);return(v==null?void 0:v.label)||"Select chart type"},T=()=>{var D,b;if(t==="custom"){const A=s.useEditorStore.getState().card,S=(D=A==null?void 0:A.customCardPreferences)==null?void 0:D.icon,O=(b=A==null?void 0:A.customCardPreferences)==null?void 0:b.componentName;if(S&&O)return e.jsx(ji,{icon:S,componentName:O});if(O){const M=et(O);if(M)return M}return e.jsx(Ge,{className:"h-4 w-4"})}const v=ss.find(A=>A.id===t);if(v){const A=v.icon;return e.jsx(A,{className:"h-4 w-4"})}return e.jsx(Ge,{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-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(v=>{if(v==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:D=>y(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ss.map(D=>{const b=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>C(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(v==="standardPlugin"){const D=n.filter(b=>b.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:b=>y(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(b=>b.componentType==="chart").map((b,A)=>e.jsx(bt,{pluginVisual:b,index:A,onSelect:()=>k(b)},`${b.url}-${b.name}-${A}`))},"standardPlugin"):null}if(v==="customPlugin"){const D=n.filter(b=>b.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:b=>y(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((b,A)=>e.jsx(bt,{pluginVisual:b,index:A,onSelect:()=>k(b)},`${b.url}-${b.name}-${A}`))},"customPlugin"):null}return null})]})]})})]})})}const ji=({icon:t,componentName:a})=>{const n=hs(),r=et(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ge,{className:"h-4 w-4"})},Sn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ye,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ts,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})})};function yi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=I.useState(t),[o,i]=I.useState(!1),c=(d=s.useEditorStore(m=>{var u;return(u=m.card.config)==null?void 0:u.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:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&o&&n!==t?(a(n),i(!1)):m.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 vi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=I.useState(null),[o,i]=I.useState(""),[c,l]=I.useState(""),d=()=>{a({...t,"":""})},m=h=>{const p={...t};delete p[h],a(p)},u=h=>{const p={...t};delete p[h],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(([h,p],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>l(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?u(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),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(h),i(h),l(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+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 Ct({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=I.useState(t??""),[l,d]=I.useState(!1);I.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(i),d(!1)},u=()=>{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:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&l&&i!==t?m():h.key==="Escape"&&u()},"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:m,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:u,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function bi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var nt;const{attributes:l,listeners:d,setNodeRef:m,transform:u,transition:h,isDragging:p}=s.useSortable({id:t.id}),f=s.useEditorStore(W=>W.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:g,handleAliasTemplateChange:C,handleValueAliasesChange:k,removeField:R,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:b}=Zs(f),[A,S]=I.useState(!1),[O,M]=I.useState(t.dateFormat||"YYYY-MM-DD"),[E,N]=I.useState(t.customFormat||""),[L,B]=I.useState(!!t.customFormat),[P,V]=I.useState(t.granularity||"day"),[q,X]=I.useState(t.aliasTemplate||""),[K,$]=I.useState(t.valueAliases||{}),F=W=>{W==="custom"?B(!0):(B(!1),M(W),a==="groupBy"&&y(n,W,""))},U=W=>{N(W),a==="groupBy"&&y(n,"custom",W)},_=W=>{var qe;V(W);const xe=(qe=H(W)[0])==null?void 0:qe.value;xe&&!L&&(M(xe),a==="groupBy"&&y(n,xe,"")),a==="groupBy"&&g(n,W)},Y=W=>{X(W),a==="metrics"&&C(n,W)},Q=W=>{$(W),a==="metrics"&&k(n,W)},G=W=>{j(a,n,W)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(u),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},z=H(P),J=!oe&&a!=="pivotBy",ie=se&&a==="groupBy",Ne=!oe&&se&&a==="groupBy",Te=oe&&se&&a==="groupBy",ne=oe&&a==="metrics"&&((nt=f.config)==null?void 0:nt.comparisonType)==="target",le=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:W=>{W.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),kn=()=>J?e.jsx(Ct,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,tt=()=>ie?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:P,onValueChange:_,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,Tn=()=>Ne?e.jsxs(e.Fragment,{children:[tt(),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:L?"custom":O,onValueChange:F,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:z.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),L&&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:E,onChange:W=>{W.stopPropagation(),U(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,En=()=>{var W,ge,xe,qe,at;return Te?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=f.config)==null?void 0:W.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:((ge=f.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:w})]})}),((xe=f.config)==null?void 0:xe.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((qe=f.config)==null?void 0:qe.trendlineWindow)||30,onChange:An=>{const Ln=parseInt(An.target.value)||30;v(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:((at=f.config)==null?void 0:at.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},In=()=>{var W,ge;return ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Ct,{value:((W=f.config)==null?void 0:W.targetValue)!==void 0&&((ge=f.config)==null?void 0:ge.targetValue)!==null?String(f.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?b(Number(xe)):b(0)},placeholder:"Enter target value...",type:"text"})]}):null},Mn=()=>le?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{x(n,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(bn,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(yi,{aliasTemplate:q,onAliasTemplateChange:Y}),e.jsx(vi,{valueAliases:K,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:m,style:te,...l,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Sn,{dataType:ae}),e.jsx(Js,{className:"w-[140px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),o(ge)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[ce(),kn(),c==="kpi"&&tt(),Tn(),En(),In(),Mn()]})]})}function Ni({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 Ze({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(),m=s.useEditorStore(j=>j.card),u=s.useEditorStore(j=>j.card.type),h=a.length>0,p=(j,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(C=>C.id===j)===-1||d(m.id,j,{direction:x})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Ni,{concept:t})]}),e.jsx("div",{ref:l,className:`min-h-[60px] rounded-lg border-2 border-dashed p-2 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((j,x)=>{const g=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(bi,{field:j,zone:t,index:x,sortDirection:g,onSortDirectionChange:C=>p(j.id,C),hasPivotColumns:i,cardType:u})})},j.id)})})})})]})}function Ci({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),i=o==null?void 0:o.type,c=t.length>0||n.length>0,l=i!=="kpi",d=i!=="kpi"&&c,m=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},u=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"w-full space-y-4",children:[e.jsx(Ze,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),l&&e.jsx(Ze,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:n,label:u().label,placeholder:u().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Ze,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Si({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=s.useEditorStore(h=>h.showAIDialog),l=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(h=>h.card),{data:u}=s.useDashboardCardQuery(m);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(gi,{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||u}),children:e.jsx(ms,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Ta,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6",children:[e.jsx(Ci,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function wi({initialFilters:t,availableFields:a}={}){const[n,r]=I.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"},m=T=>{const w=v=>{if(v.id===T){const D=l[0]||d;return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},u=T=>{const w=v=>{if(v.id===T){const D=l[0]||d;return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},h=(T,w)=>{const v=D=>D.id===T?{...D,conditions:D.conditions.filter(b=>b.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},p=(T,w)=>{const v=D=>D.id===T?{...D,groups:D.groups.filter(b=>b.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},f=(T,w,v,D)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const b=A=>A.id===T?{...A,conditions:A.conditions.map(S=>S.id===w?{...S,[v]:D}:S)}:{...A,groups:A.groups.map(b)};r(b(n))},j=(T,w,v)=>{const D=b=>b.id===T?{...b,conditions:b.conditions.map(A=>A.id===w?{...A,...v}:A)}:{...b,groups:b.groups.map(D)};r(D(n))},x=(T,w)=>{const v=D=>D.id===T?{...D,logicalOperator:w}:{...D,groups:D.groups.map(v)};r(v(n))},y=(T,w)=>{const v=D=>D.id===T?{...D,negate:w}:{...D,groups:D.groups.map(v)};r(v(n))},g=(T,w,v)=>{const D=b=>b.id===T?{...b,conditions:s.arrayMove(b.conditions,w,v)}:{...b,groups:b.groups.map(D)};r(D(n))},C=(T,w,v)=>{const D=b=>b.id===T?{...b,groups:s.arrayMove(b.groups,w,v)}:{...b,groups:b.groups.map(D)};r(D(n))},k=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const w=D=>{let b="";typeof D.field=="object"?b=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:b=String(D.field);const A=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date")(typeof S=="string"||S instanceof Date)&&(S=`DATE('${S}')`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(S)?O=S.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof S=="string"?O=S.split(",").map(M=>{const E=M.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(O=[String(S)]),S=`(${O.join(", ")})`}switch(A){case"contains":return typeof S=="string"?`${b} LIKE '%${S.replace(/'/g,"")}'`:`${b} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${b} LIKE '${S.replace(/'/g,"")}%'`:`${b} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${b} LIKE '%${S.replace(/'/g,"")}'`:`${b} LIKE '%${String(S)}'`;default:return`${b} ${A} ${S}`}},v=D=>{const b=D.conditions.map(w),A=D.groups.map(E=>v(E)),S=[...b,...A].filter(Boolean);if(S.length===0)return"";const O=S.join(` ${D.logicalOperator} `),M=S.length>1?`(${O})`:O;return D.negate?`NOT ${M}`:M};return v(T)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:m,addGroup:u,removeCondition:h,removeGroup:p,updateCondition:f,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:y,reorderConditions:g,reorderGroups:C,generateSQLPreview:k,hasAnyFilters:R}}function Di({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 ki=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(oa,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Ti=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ei({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=I.useState(!1),l=I.useMemo(()=>{const d={};return n.forEach(m=>{const u=Ti(m);d[u]||(d[u]={}),d[u][m.entityId]||(d[u][m.entityId]=[]),d[u][m.entityId].push(m)}),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(Di,{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,m])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(m).map(([u,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[ki(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.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}-${u}`))},d))})]})})]})}function st(t){var j;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]},m=((j=a.dataSource)==null?void 0:j.connectionId)||a.connectionId,{data:u,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function Ii({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=ue.useState(!1),{filterValues:l}=st(t),d=u=>{n(a.filter(h=>h!==u))},m=u=>{a.includes(u)?n(a.filter(h=>h!==u)):n([...a,u])};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(u=>{const h=l.find(p=>p.value===u);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&d(u)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(u)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:l.map((u,h)=>e.jsxs(s.CommandItem,{onSelect:()=>m(u.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+h))})]})]})})]})})}const wn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=wn(n)}),a};function Mi({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:l}=st(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,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Ai=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Li=["=","!=","contains","startsWith","endsWith","in","not in"],Oi=["=","!=",">",">=","<","<=","in","not in"],Ri=["=","!="],Fi=["=","!=",">",">=","<","<=","in","not in"];function Bi(t){switch(t){case"string":return Li;case"number":return Oi;case"boolean":return Ri;case"date":return Fi;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:m,listeners:u,setNodeRef:h,transform:p,transition:f,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:y}=st(t.field),g={transform:s.CSS.Transform.toString(p),transition:f};return e.jsxs("div",{ref:h,style:g,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...u,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:C=>c(n,C),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(Ei,{value:t.field,onValueChange:C=>{d(n,t.id,{field:C,value:""})},availableFields:l,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?d(n,t.id,{operator:C,value:[]}):d(n,t.id,{operator:C,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(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:C},C))})]}),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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Ii,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Mi,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>d(n,t.id,{value:C}),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:C=>d(n,t.id,{value:C==="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:C=>o(n,t.id,"value",C.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 zi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:u,onAddCondition:h,onAddGroup:p,availableFields:f,renderFilterGroup:j,updateConditionFields:x}){const{attributes:y,listeners:g,setNodeRef:C,transform:k,transition:R,isDragging:T}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(k),transition:R},v=b=>{const{active:A,over:S}=b;if(S&&A.id!==S.id){const O=t.conditions.findIndex(E=>E.id===A.id),M=t.conditions.findIndex(E=>E.id===S.id);O!==-1&&M!==-1&&m(t.id,O,M)}},D=b=>{const{active:A,over:S}=b;if(S&&A.id!==S.id&&n){const O=t.groups.findIndex(E=>E.id===A.id),M=t.groups.findIndex(E=>E.id===S.id);O!==-1&&M!==-1&&u(n,O,M)}};return e.jsxs("div",{ref:C,style:w,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",{...y,...g,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:b=>r(t.id,b),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:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((b,A)=>e.jsx(Dn,{condition:b,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},b.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(b=>j(b,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>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:m,removeCondition:u,removeGroup:h,updateCondition:p,updateConditionFields:f,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:y,reorderGroups:g,generateSQLPreview:C,hasAnyFilters:k,setCurrentFilters:R}=wi({initialFilters:t,availableFields:a}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=I.useState(!1),D=(S,O,M)=>{const E=N=>N.id===S?{...N,conditions:N.conditions.map(L=>L.id===O?{...L,field:M,dataType:M.dataType}:L)}:{...N,groups:N.groups.map(E)};R(E(i))},b=(S,O=0,M)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:N,over:L}=E;if(L&&N.id!==L.id){const B=S.conditions.findIndex(V=>V.id===N.id),P=S.conditions.findIndex(V=>V.id===L.id);B!==-1&&P!==-1&&y(S.id,B,P)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,N)=>e.jsx(Dn,{condition:E,index:N,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:u,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:f},E.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:N,over:L}=E;if(L&&N.id!==L.id){const B=S.groups.findIndex(V=>V.id===N.id),P=S.groups.findIndex(V=>V.id===L.id);B!==-1&&P!==-1&&g(S.id,B,P)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>b(E,O+1,S.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(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(zi,{group:S,depth:O,parentGroupId:M,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:D,onRemoveCondition:u,onReorderConditions:y,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:b,updateConditionFields:f},S.id),A=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..."})]}):b(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:w,onCheckedChange:S=>v(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(k?i:null),children:"Apply Filters"})]})]})}function Vi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const l=m=>{n(t,m),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:m=>{m.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(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]=I.useState(null),c=s.useEditorStore(j=>j.card),l=(f=c==null?void 0:c.config)==null?void 0:f.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=I.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||a.find(x=>x.id===j)?"source":n("groupBy").find(x=>x.id===j)?"groupBy":n("metrics").find(x=>x.id===j)?"metrics":n("pivotBy").find(x=>x.id===j)?"pivotBy":n("sortBy").find(x=>x.id===j)?"sortBy":null,[a,n]),u=I.useCallback(j=>{i(j.active.id)},[]),h=I.useCallback(j=>{const{active:x,over:y}=j;if(!y||!t){i(null);return}const g=x.id,C=y.id,k=m(g),R=m(C)||C;if(k==="source"&&R==="sortBy"){i(null);return}if(k==="source"&&R!=="source"&&R!=="sortBy"){const T=[...a].find(b=>b.id===g);if(!T){i(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const b=w[0].qualifiedEntityName;if(!b){i(null);return}if(b!==T.qualifiedEntityName&&T.qualifiedEntityName)if(l){if(!Cn(b,T.qualifiedEntityName,l)){Is(),i(null);return}}else{Is(),i(null);return}}const v=n(R);if(Ms(T,v)){i(null);return}const D=s.getNewField(T,R);i(null),r(R,[...v,D]);return}if(k&&R&&k!=="source"&&R!=="source"&&k!==R){const T=n(k),w=n(R),v=T.find(A=>A.id===g);if(!v){i(null);return}const D=s.getNewField(v,R);if(i(null),R==="sortBy"){if(k==="pivotBy"){i(null);return}Ms(v,w)||r(R,[...w,D]);return}const b=T.filter(A=>A.id!==g);r(k,b),r(R,[...w,D]);return}if(k&&R&&k===R&&k!=="source"){const T=n(k),w=T.findIndex(D=>D.id===g),v=T.findIndex(D=>D.id===C);if(w!==v){const D=s.arrayMove(T,w,v);r(k,D)}}i(null)},[t,a,n,r,m,l]),p=o?d.find(j=>j.id===o):null;return{activeId:o,activeField:p,handleDragStart:u,handleDragEnd:h}}function Ui({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=be();r==null||r.role;const[o,i]=I.useState(!1),c=s.useEditorStore(g=>g.isDevMode),l=s.useEditorStore(g=>g.card),d=s.useEditorStore(g=>g.card.dataSource);s.isExplorerCard(l);const{config:m}=I.useContext(s.SemaphorContext).tokenProps,u=(m==null?void 0:m.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(g=>g.showAIDialog),f=s.useEditorStore(g=>g.frame),j=s.useManagementStore(g=>g.selectedVisual),x=(j==null?void 0:j.id)===(f==null?void 0:f.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!u&&"justify-end"),children:[u&&t&&!p&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{i(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx($s,{}),n&&!x&&e.jsx(qs,{variant:"default"}),x&&e.jsx(Wr,{}),a&&s.isDevEnv]}),o&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:o,onOpenChange:i,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function qi({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 Yi(){var d,m;const t=s.useEditorStore(u=>u.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=I.useState(!1),[o,i]=I.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(t.id,parseInt(u))},l=u=>{const h=u.target.value;i(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:$i.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function Gi({isOpen:t,onClose:a}){const n=Gt(a,{enabled:t}),r=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(u=>u.card),i=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(u=>{var h;return((h=u.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:l}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),m=I.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:m&&e.jsx(I.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{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:m,columns:u,columnsLoading:h,columnsError:p}){var L;const f=s.useEditorStore(B=>B.card);s.useEditorStore(B=>B.frame);const j=s.useDashboardStore(B=>B.filterValues),{updateCardConfig:x,setCard:y,updateCardInFrame:g}=s.useEditorActions(),C=s.useEditorStore(B=>B.showAIDialog),[k,R]=I.useState(!1),T=s.useEditorStore(B=>{var P;return((P=B.card.customCardPreferences)==null?void 0:P.url)&&B.card.type==="custom"}),{data:w,errorMessage:v,isPending:D,isLoading:b,isFetching:A,pagination:S}=s.useDashboardCardQuery(m),O=(B,P)=>{const V={...m,paginationConfig:{page:B+1,pageSize:P}};y(V),g(V)};function M(){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(j||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":p?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const E=B=>{if(!f.config)return;if(!B.length){x(f.id,{...f.config,sortByColumns:[]});return}const P=f.config,V=B.map(({id:q,desc:X})=>{var U,_;const K=(U=P.metricColumns)==null?void 0:U.find(Y=>Y.label===q),$=(_=P.groupByColumns)==null?void 0:_.find(Y=>Y.label===q),F=K||$;return F?{id:s.getFieldId("sortBy",F),name:F.name,dataType:F.dataType,label:F.label,qualifiedEntityName:F.qualifiedEntityName,entityId:F.entityId,entityName:F.entityName,entityType:F.entityType,role:"sortby",direction:X?"desc":"asc"}:null}).filter(q=>q!==null);x(f.id,{...P,sortByColumns:V})},N=I.useMemo(()=>{var B,P;return(P=(B=f.config)==null?void 0:B.sortByColumns)==null?void 0:P.map(V=>({id:V.label,desc:V.direction==="desc"}))},[(L=f.config)==null?void 0:L.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Ui,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:l,filterCount:d}),n&&M(),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"&&C&&e.jsx(hn,{variant:"outline"}),e.jsx(qi,{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(Yi,{})}),C&&e.jsx(ms,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(xn,{})})]}),!k&&T&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>R(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(wa,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(pn,{})}),t==="table"&&(w==null?void 0:w.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:m,data:(w==null?void 0:w.records)||[],paginationMetadata:S,onPaginationChange:O,isLoading:b||A,onSortChange:E,sortState:N})}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(w==null?void 0:w.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(rn,{sql:w==null?void 0:w.sql,error:v})]})})]}),e.jsx(Gi,{isOpen:k,onClose:()=>R(!1)})]})]})}function Qi({activeField:t}){const[a,n]=I.useState(!0);return I.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 Ki=()=>{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 $,F;const[t,a]=I.useState("chart"),[n,r]=I.useState(!1),[o,i]=I.useState(!1),[c,l]=I.useState(!0),d=s.useEditorStore(U=>U.showAIDialog),m=s.useDashboardStore(U=>U.isVisualEditing),{setCardType:u}=s.useEditorActions(),h=s.useEditorStore(U=>U.card.type);I.useEffect(()=>Ki(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},f=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{i(!0)},y=U=>{u(U)},g=s.useEditorStore(U=>U.frame),C=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.activeTabCardId),s.useEditorStore(U=>U.actions.getAvailableFields);const{addCard:k,removeCard:R,updateCard:T,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:D=[],isLoading:b,error:A}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=C,{getFieldsForContainer:M,setFieldsForContainer:E}=Zs(O),{activeField:N,handleDragStart:L,handleDragEnd:B}=_i({activeCardId:g.activeCardId,sourceFields:D,getFieldsForContainer:M,setFieldsForContainer:E}),P=(U,_)=>{_&&v(U,_)},V=U=>{var _;T(U,{config:{...(_=g.cards.find(Y=>Y.id===U))==null?void 0:_.config,filters:void 0}})},q=D,X=U=>{if(!U)return 0;let _=U.conditions.length;return U.groups.forEach(Y=>{_+=X(Y)}),_},K=X((($=O==null?void 0:O.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:L,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(xi,{isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Si,{selectedChart:h,onChartChange:y,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy")}),e.jsx(Hi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:f,onAdvancedToggle:j,onFiltersClick:x,filterCount:K,activeCard:O,dataSourceState:C.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:b,columnsError:A,getFieldsForContainer:M,cards:g.cards,activeCardId:g.activeCardId,addCard:k,setActiveCard:w})]}),!c&&m&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(Vi,{cardId:O.id,filters:((F=O.config)==null?void 0:F.filters)||null,onFiltersChange:P,onClearFilters:V,availableFields:q,isOpen:o,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Qi,{activeField:N||null})})]})}function Ji({authToken:t,onSave:a,onClose:n}){const r=I.useRef(null),o=s.useEditorStore(C=>C.showAIDialog),i=s.useEditorStore(C=>C.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:l,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:u,handleDragEnd:h,handleDragStart:p,handleDragCancel:f,sensors:j}=Br();I.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),I.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),I.useEffect(()=>{var C,k;o?((C=r.current)==null||C.resize(40),l(!0)):(l(!1),(k=r.current)==null||k.resize(0))},[o,l]);function x(C){C<1?l(!1):o||l(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(nn,{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(yt,{})})]})]})}function g(){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(yt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:u,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):g()})}function Xi(){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 Zi(){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}=yn();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(_s,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function el(){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(nn,{type:"filter",ColumnsComponent:()=>e.jsx(Zi,{})})})]})}function sl(){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 tl(){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(sl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(el,{})})]})}function nl(){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 al({showControls:t=!1,showFooter:a=!0,...n}){return typeof window>"u"?null: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(nl,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Ar,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Xi,{}),e.jsx(tl,{})]})]})]})]})})}exports.DashboardPlus=al;exports.ResourceManagementPanel=sn;exports.ScheduleDashboard=Bt;exports.SelectComponent=Pe;exports.cleanCard=Ot;exports.downloadPdf=Ft;exports.getDashbaordStateWithoutData=ns;
|