react-semaphor 0.0.545 → 0.0.547

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var nt=t=>{throw TypeError(t)};var hs=(t,a,n)=>a.has(t)||nt("Cannot "+n);var re=(t,a,n)=>(hs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?nt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(hs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(hs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-CGfbd0m4.js"),M=require("react");require("react-dom");function Mn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Mn(M);var be,Ne,de,fe,ge,Ye,Ns,Nt,Ln=(Nt=class extends s.Subscribable{constructor(a,n){super();Oe(this,ge);Oe(this,be);Oe(this,Ne);Oe(this,de);Oe(this,fe);Be(this,be,a),this.setOptions(n),this.bindMethods(),Fe(this,ge,Ye).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,be).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,be).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this,a)}getCurrentResult(){return re(this,Ne)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this)}mutate(a,n){var r;return Be(this,fe,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,be).getMutationCache().build(re(this,be),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},be=new WeakMap,Ne=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakSet,Ye=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Ne,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Ns=function(a){s.notifyManager.batch(()=>{var n,r,o,l,c,i,d,u;if(re(this,fe)&&this.hasListeners()){const h=re(this,Ne).variables,m=re(this,Ne).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,fe)).onSuccess)==null||r.call(n,a.data,h,m),(l=(o=re(this,fe)).onSettled)==null||l.call(o,a.data,null,h,m)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,fe)).onError)==null||i.call(c,a.error,h,m),(u=(d=re(this,fe)).onSettled)==null||u.call(d,void 0,a.error,h,m))}this.listeners.forEach(h=>{h(re(this,Ne))})})},Nt);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Ln(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:l,mutateAsync:o.mutate}}/**
1
+ "use strict";var nt=t=>{throw TypeError(t)};var hs=(t,a,n)=>a.has(t)||nt("Cannot "+n);var re=(t,a,n)=>(hs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?nt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(hs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(hs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-N4c87NYQ.js"),M=require("react");require("react-dom");function Mn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Mn(M);var be,Ne,de,fe,ge,Ye,Ns,Nt,Ln=(Nt=class extends s.Subscribable{constructor(a,n){super();Oe(this,ge);Oe(this,be);Oe(this,Ne);Oe(this,de);Oe(this,fe);Be(this,be,a),this.setOptions(n),this.bindMethods(),Fe(this,ge,Ye).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,be).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,be).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this,a)}getCurrentResult(){return re(this,Ne)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this)}mutate(a,n){var r;return Be(this,fe,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,be).getMutationCache().build(re(this,be),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},be=new WeakMap,Ne=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakSet,Ye=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Ne,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Ns=function(a){s.notifyManager.batch(()=>{var n,r,o,l,c,i,d,u;if(re(this,fe)&&this.hasListeners()){const m=re(this,Ne).variables,h=re(this,Ne).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,fe)).onSuccess)==null||r.call(n,a.data,m,h),(l=(o=re(this,fe)).onSettled)==null||l.call(o,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,fe)).onError)==null||i.call(c,a.error,m,h),(u=(d=re(this,fe)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(re(this,Ne))})})},Nt);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Ln(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:l,mutateAsync:o.mutate}}/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -33,12 +33,12 @@
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const Vn=s.createLucideIcon("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
36
+ */const _n=s.createLucideIcon("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
37
37
  * @license lucide-react v0.453.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const _n=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
41
+ */const Vn=s.createLucideIcon("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
42
42
  * @license lucide-react v0.453.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
@@ -403,7 +403,7 @@
403
403
  *
404
404
  * This source code is licensed under the ISC license.
405
405
  * See the LICENSE file in the root directory of this source tree.
406
- */const je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Lt(c))}})}})}}function Lt(t){return{...t,customCfg:Ea(t.customCfg),data:[]}}function Ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ta(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Cs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ia(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(p=>p.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,h]=M.useState(!1),m=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:x}=s.useSemaphorContext();async function g(){d(!0);const p=Bs(m),v=await Ta(t,p,f,x==null?void 0:x.accessToken);v&&(l([...o||[],v]),c(v.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:h,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ma(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(h){l(h)}async function d(h){if(await Ia(h,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(x=>x.id!==h);o(f||[]),l("original")}}async function u(h){const m=n==null?void 0:n.map(g=>g.id===h.id?{...g,isDefault:!h.isDefault}:{...g,isDefault:!1});o(m||[]);const f={...h,isDefault:!h.isDefault};await Cs(f,c==null?void 0:c.accessToken);const x=n==null?void 0:n.find(g=>g.isDefault);if(x&&x.id!==h.id){const g={...x,isDefault:!1};await Cs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(oa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:m=>{m.preventDefault(),u(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:m=>{m.preventDefault(),d(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Rt(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ot(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,m=document.createElement("a");m.href=h;const f=`${o}-${new Date().toISOString()}.pdf`;m.download=f,m.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function La({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ot()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ct=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Ra(),[i,d]=M.useState(""),[u,h]=M.useState(ct[0].value),[m,f]=M.useState("06:00"),[x,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:p=>d(p.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:x,onChange:p=>{g(p.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ct,value:u,onValueChange:p=>h(p)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:m,onChange:p=>f(p.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:u,time:m,subject:x}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(p=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(p.frequency)," "]}),e.jsx(s.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(dt,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(dt,{tooltip:`${p.endUserEmail}`,children:e.jsx(pa,{className:"size-3.5"})}),c===p.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const dt=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Ra(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,l]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",m={dashboardId:i,endUserId:u},{data:f,isLoading:x,isError:g,isFetching:p,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",m),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...D}=Rt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:x,isFetching:p,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function cs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function Ft(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Oa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Fa=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},Va=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)},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ua=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Oa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Ka(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Fa((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Qa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>za((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Pa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Va((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Ya(){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 remove resource shares: ${n.message}`)}})}function Xa(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ua((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function Za(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>$a((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function er(t,a){return Za(ee.VISUAL,t,a)}function zt(){const[t,a]=M.useState(new Map),n=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=M.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Pt(t,a,n){var m;const r=Ga(t),o=Ha(t,n),l=Ka(t),c=Qa(t,a),i=Wa(t),d=Ja(),u=Ya(),h={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((m=r.data)==null?void 0:m[h[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function sr(t,a){return Pt(ee.DASHBOARD,t,a)}function tr(t,a){return Pt(ee.VISUAL,t,a)}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ar({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:h,formatDate:m}){var E;const{selectVisual:f}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),[g,p]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(p(!0),j(!0)):v&&(p(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",x&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&x,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&x,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:p,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(ya,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),h(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function Vt({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function es({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function _t({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(l=>n(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function Ut({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function $t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function or(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ir({user:t}){return Gt(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function lr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=rr((r==null?void 0:r.type)||""),i=n.some(m=>m.id===t.id),d=n.find(m=>m.id===t.id),u=d?d.newRole:a==null?void 0:a.role,h=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(es,{currentRole:u,onRoleChange:m=>{l(t.id,a.role,m)},roleOptions:h,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:xe(u,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function ur({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],h=c.orgUsersOnly||[],m=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,x)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",p=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=xe(f.role,n(p));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})]},x)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,x)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",p=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=xe(f.role,n(p));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})]},x)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,x)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},x)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,x)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},x)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,x)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},x)})})]}),!i.length&&!d.length&&!u.length&&!h.length&&!m.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var x,g;const h=((x=a.find(p=>p.id===d.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=a.find(p=>p.id===d.tenantUserId))==null?void 0:g.type)||"",f=xe(d.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const h=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,x;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",h=((x=a.find(g=>g.id===i.tenantUserId))==null?void 0:x.type)||"",m=xe(i.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=xe(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:h,handleRemoveAccess:m,handleUpdateAccess:f,handleUserRoleChange:x}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?h(t.id):m(t.id):h(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(ir,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(es,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(lr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>x(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(dr,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),x=s.useShareSearchQuery(),g=s.useShareManagementActions(),p=c||(E=>{const S=h.some(D=>D.id===E),N=m.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,R=m;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(ur,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(mr,{isInitialLoading:a,isSearching:n,searchQuery:x,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?or(E,t,l):void 0,N=R.includes(E.id),D=!!S,w=D&&!N,L=h.some(A=>A.id===E.id),k=h.find(A=>A.id===E.id),O=r(E.type);return e.jsx(hr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:L,selectedUser:k,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(Se,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const De=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function xr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=De().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",m=o?o.newRole:h,f=a.role!=="NONE"&&!l&&(!o||o.newRole===h),x=o!==null&&o.newRole!==h,g=l,p=h==="NONE"||!h,v=b=>{switch(b){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ca,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(h,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",x&&!g&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),x&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(b=>e.jsxs(s.Button,{variant:m===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Qt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,m=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,x=(p,v)=>{l(p,v)},g=()=>{c()};return e.jsx(xr,{currentUser:t,currentShare:m,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:x,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const pr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=fr(c),h=Xa(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function gr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var W,_;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:h,debouncedSearchQuery:m}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:D}=we({debouncedSearchQuery:m,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),k=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=f.some(Z=>Z.id===$),U=x.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(_=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:_[0];M.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&j.setOrgWideRole(V.role)},[b,V,j]);const P=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Vt,{value:u,onChange:h}),e.jsx(_t,{selectedUsers:f,selectedUserObjects:k,onRemove:O,onRoleChange:A,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:x,allUsers:L,onRemove:y}),e.jsx($t,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:De}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Qt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:p==="allOrgUsers"&&v!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:v}:null,allUsersToRemove:p==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function ut({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:k,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=h.some(K=>K.id===G),te=m.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},T=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},V=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},P=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},_=(()=>{var G,Z,te,ae;return x==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:x==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=D.filter(G=>h.some(Z=>Z.id===G.id)),q=L||O,U=k||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(at,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vt,{value:i,onChange:u}),e.jsx(_t,{selectedUsers:h,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:m,allUsers:D,onRemove:F}),e.jsx($t,{usersToUpdate:f,allUsers:D,onRemove:z,getRoleOptions:De}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:D,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Qt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Y,allUsersToUpdate:x==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||g!==_.role)||x==="allTenants"&&((_==null?void 0:_.role)===void 0||p!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:x==="allTenantUsers"?g:p}:null,allUsersToRemove:x==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||x==="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(at,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),h=M.useMemo(()=>f=>s.validateShareData(f),[]),m=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:h,isCurrentStateValid:m,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function mt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const h=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const x=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,k,O,A;if(R)return"Updating...";if(i==="specific_users"){if(h.length===0&&m.length===0&&f.length===0)return"Select users to share with";const I=h.length+m.length+f.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:f.length>0&&h.length===0&&m.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return p===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(h.length===0&&m.length===0&&f.length===0)return"Select users to share with";const I=h.length+m.length+f.length;return I===0?"Select users to share with":h.length>0&&m.length>0?`Update access for ${I} user${I!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:f.length>0&&h.length===0&&m.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!x||i==="specific_tenant_users"&&!x?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},D=()=>{var L,k,O,A;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const F={...T,updateAccess:!0};l(F)}}}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(p===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}},w=()=>{var L,k,O,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"default";const y=I.role;return p===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||m.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function jr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const m=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:x,isCurrentStateValid:g}=Wt(),p=a||n||r,v=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&h.length===0)return"Select users to share with";const E=d.length+u.length+h.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&h.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&u.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return m===E?"Remove Access":"Update Access"}return"Share"},j=()=>p||!t?!0:!g,b=()=>{const E=f();E&&x(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&x(E)&&o(E)}else{const E=i.role;if(m===E){const N=f();if(N&&x(N)){const D={...N,removeAccess:!0};o(D)}}else{const N=f();if(N&&x(N)){const D={...N,updateAccess:!0};o(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!p&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!p&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,D,w,L;const{currentUser:d}=cs(),[u,h]=M.useState("specific_users"),[m,f]=M.useState("specific_users"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return m;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=M.useCallback(()=>{x.resetShareState(),l()},[x,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:k=>{const O=k;x.setSelectedTab(O),x.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(gr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>h(k),isSharing:n,isUpdating:o,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>h(k),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(mt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:m,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(mt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(jr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Yt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(m,{onSuccess:()=>{i()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(f=>{var g,p;const x=(p=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:p.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(x==null?void 0:x.role)||"VIEWER"}}));l(m,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(m=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:m.id,role:m.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h,tenantId:m}=t;if(u&&u.length>0){const f=Ce(n,r,u.map(x=>{var p,v;const g=(v=(p=c==null?void 0:c.shares)==null?void 0:p.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===x);return{scope:"specific_tenant_user",tenantUserId:x,tenantId:m,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(h&&h.length>0&&h.forEach(f=>{const x=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:m,role:f.newRole}]);o(x,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(x=>({scope:"specific_tenant_user",tenantUserId:x.id,tenantId:m,role:x.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:h}=t;if(d&&d.length>0){const m=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(m,{onSuccess:()=>{i()}})}if(u&&u.length>0){const m=Ce(n,r,u.map(f=>{var g,p;const x=(p=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:p.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(x==null?void 0:x.role)||"VIEWER"}}));l(m,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(m=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:m.id,role:m.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Xt(t,a,n,r){var u,h,m,f,x,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const p=Ce(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const p=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(p){const j=(h=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:h[0];if(j){const b=Ce(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(m=i==null?void 0:i.shares)==null?void 0:m.tenantWide)==null?void 0:f[0];if(j){const b=Ce(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(x=i==null?void 0:i.shares)==null?void 0:x.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function yr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(m,f)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",m)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(m=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(m,f)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const m={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",m)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:h}}function br(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Fs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Nr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function ht(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Cr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function Sr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),r=Fs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatamodelId),c=s.useEditorStore(x=>x.selectedDatabaseName),i=s.useEditorStore(x=>x.selectedTableName),d=s.useEditorStore(x=>x.selectedConnectionId),u=s.useEditorStore(x=>x.isShowingVisual),h=n.sql,m=M.useCallback(()=>{var j;let x=h;h&&!h.includes("{{")&&(x=br(h),t(x));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,p={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:x,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?p:b);return{...a,cards:v,activeCardId:Nr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,h]);return console.log("getUpdatedFrame",m()),{getUpdatedFrame:m}}function zs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:h}=s.useDashboardActions(),m=s.useDashboardStore(p=>p.selectedSheetId),f=er((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),x=M.useCallback(async p=>{try{r(p);const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",p.id,a);return Cr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=M.useCallback(async p=>{try{if(r(p),!m)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",p.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(m,C,"end"),c(!0),d(C.id),h(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,m,u,c,d,h]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:x,handleAddLibraryVisual:g,getUpdatedFrame:Sr().getUpdatedFrame,refetch:f.refetch}}function wr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[h,m]=M.useState(null),[f,x]=M.useState(!1),[g,p]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=zs(),{resources:S,isLoading:N,isError:D,createResource:w,updateResource:L,deleteResource:k,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:F,isRemovingShares:z,isUpdatingShares:V}=tr(()=>{x(!1),p(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Y}=vr((h==null?void 0:h.id)||null,A,T);cs();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),_=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{p(B),x(!0)},U=()=>{g&&k(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=zt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{E(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{m(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ft,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(ar,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:_},B.id))})}),d&&h&&e.jsx(Jt,{resource:h,resourceType:ee.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:V,onClose:()=>{u(!1),m(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:B=>{!B&&y||(x(B),B||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:h,onDashboardItemClick:m}){var E;const{selectDashboard:f}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),[g,p]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(p(!0),j(!0)):v&&(p(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(t.id),m==null||m(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",x&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&x,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&x,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:p,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Dr({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Er(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[l,c]=M.useState(""),[i,d]=M.useState(""),[u,h]=M.useState(!1),[m,f]=M.useState(null),[x,g]=M.useState(!1),[p,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:D,updateResource:w,deleteResource:L,duplicateResource:k,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:F,removeResourceShares:z}=sr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:P}=yr((m==null?void 0:m.id)||null,F,z),{currentUser:Y}=cs(),W=E.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),_=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&D({title:l,description:i,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{p&&L(p.id)},Q=K=>{b(K),k(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=zt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=E.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{f(K),Y==null||Y.type,h(!0)};return we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ft,{}):N?e.jsx(Dr,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:l,onChange:K=>c(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:K=>d(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:K=>n(K.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ra,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(kr,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&m&&e.jsx(Jt,{resource:m,resourceType:ee.DASHBOARD,onShare:V,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{h(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:x,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(x=>x.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(x=>x.actions),{currentUser:c}=cs(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),h=qt(a,{enabled:t}),m=x=>{},f=x=>{console.log("Editing dashboard:",x)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:h,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Er,{onLoadDashboard:m,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(wr,{})})]})})]})})}function Tr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,h]=M.useState(!1),m=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),x=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),p=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:D,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>D||w,[D,w]),k=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,F),C(F.id)},O=()=>{E(!0)};async function A(){if(h(!0),!r||!o)return;const T=Bs(l),F=JSON.stringify(T),z={...o,template:F,filterValues:x};await Cs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),h(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(La,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(Ma,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(It,{className:"h-4 w-4"})}),!p&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:m,onClose:()=>f(!1)})]})]})}function Ir({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const h=ue.useRef(null),[m,f]=ue.useState(!1),[x,g]=ue.useState("100%"),p=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{h.current&&g(h.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),f(!1)}return e.jsxs(s.Popover,{open:m,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":m,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:x},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Tt,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:h="combobox"}){const m=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ja,{className:"size-4"});if(t==="Table")return e.jsx(ls,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function x(){return e.jsxs(s.Select,{disabled:u,value:m,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,v)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:m,children:m})]})})]})}function g(){return e.jsx(Ir,{icon:f(),items:a,value:m,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?x():g()})})}function Ar({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),h=s.useEditorStore(p=>p.actions.setSqlGen),m=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function x(p,v){var R;const j=s.createSqlGenConfig(p,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;h(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(m(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>x(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>x(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>x(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>x(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>x(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Ps({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Ue,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function xs({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Ps,{column:t}),e.jsx("span",{children:t.column_name})]})}function Mr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Lr({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.groupByColumns}),o=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.metricColumns}),l=s.useEditorStore(h=>{var m;return(m=h.card.queryConfig)==null?void 0:m.filterColumns});function c(h){return i(h)||d(h)||u(h)}function i(h){return r==null?void 0:r.some(m=>m.name===h.column_name)}function d(h){return o==null?void 0:o.some(m=>m.name===h.column_name)}function u(h){return l==null?void 0:l.some(m=>m.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(xs,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(xs,{column:a})}),e.jsx(Mr,{id:a.column_name,type:"column",children:e.jsx(xs,{column:a})})]})}const ps={id:"__placeholder__",role:"groupby",type:"string"},fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"metric",type:"number"},js={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Ee="droppable-group-by",Te="droppable-metrics",Ie="droppable-pivot-by",ss="sortable-group-by",Ss="sortable-metrics",ts="sortable-pivot-by",ws="droppable-filters",ks="sortable-filters",Vs="sortable-order-by";function Rr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:h,setPreviewPivotColumns:m}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:x,setFilterColumns:g,setOrderByColumns:p,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:T}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&T){const z=T.id,V=j.find(_=>_.column_name===y.id);if(!V)return;const P=s.isNumberDataType(V.data_type),Y=s.isTextDataType(V.data_type),W=s.isDateDataType(V.data_type);if(Y||W){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==ps.id);q.splice($,0,ps),d(q)}else if(T.id===Ee){c(a.length);const $=[...a,ps];d($),u(n),h(r)}}if(Y||W){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==fs.id);q.splice($,0,fs),m(q)}else if(T.id===Ie){c(l.length);const $=[...l,fs];m($),d(a),u(n),h(r)}}if(P||Y){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==gs.id);q.splice($,0,gs),u(q)}else if(T.id===Te){c(n.length);const $=[...n,gs];u($),h(r),d(a),m(l)}}if(S(V)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==js.id);q.splice($,0,js),h(q)}else if(T.id===ws){c(r.length);const $=[...r,js];h($),u(n),d(a),m(l)}}}else d(a),u(n),h(r),m(l)};function E(I){i(I.active.id),c(null),d(a),u(n),h(r),m(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:F}=I,z=[...n],V=t!==null?t:n.length,P={...I,id:pe(T),name:T,label:He(T,y),type:F,role:"metric",aggregate:y};z.splice(V,0,P),x(z)}function D(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],F=t!==null?t:l.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,F),g(y)}function k(I){var z,V,P,Y,W,_,$,q;const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(T.id===Ee||((z=T.data.current)==null?void 0:z.type)===ss)&&w(U),(Q||G)&&(T.id===Ie||((V=T.data.current)==null?void 0:V.type)===ts)?D(U):(H||Q)&&(T.id===Te||((P=T.data.current)==null?void 0:P.type)===Ss)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===ws||((Y=T.data.current)==null?void 0:Y.type)===ks)&&L(U)}if(T&&((W=T.data.current)==null?void 0:W.type)===ss&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(T&&((_=T.data.current)==null?void 0:_.type)===ts&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),H=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...l],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===Ss&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),x(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),i(null),c(null),d(a),u(n),h(r),m(l)}function O(I){const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)===Vs&&T){const z=o.findIndex(P=>_e(P.columnId)===y.id),V=o.findIndex(P=>_e(P.columnId)===T.id);if(z!==-1&&V!==-1&&z!==V){const P=[...o],[Y]=P.splice(z,1);P.splice(V,0,Y),p(P)}}}function A(){i(null),c(null),d(a),u(n),h(r)}return{handleDragOver:R,handleDragEnd:k,handleDragStart:E,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function _e(t){return`${Vs}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Or({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),m=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:x,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function D(y){var T;if(l){const F=s.createSqlGenConfig(y,o);C(F);const z=(T=S==null?void 0:S.find(P=>P.id===m))==null?void 0:T.name,V=s.getSql(F,s.fmt(t),s.fmt(a),z||"",E,d||"");V&&(j(V),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};p(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};p(F)}}}function w(y){y===!0&&(h||N)&&c?(x({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:h||"",datamodelName:s.resolveDatamodelName(N),datamodelId:m||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===N)))!==void 0}function A(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Lr,{onClick:D,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(xa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:h,setIsDevMode:m,setCardSql:f}=s.useEditorActions(),{connectionItems:x,modelItems:g,schemaItems:p,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:k,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:F,refetchModels:z,refetchSchemas:V,refetchTables:P,refetchColumns:Y,refetchConnections:W,handleConnectionChange:_,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Or,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":k?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),m(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:F,showNone:!0,onChange:$,isError:D,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!T&&(!c||c==="none")&&(!l||l==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:V,onChange:q,isError:L,isLoading:w,items:p,value:i||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:W,items:x,title:"Connection",value:r||"",onChange:_,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=x==null?void 0:x.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(fa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function h(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const x=f.toString();navigator.clipboard.writeText(x),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function m(){l(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:h,onMouseDown:m,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(la,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},xt=M.createContext&&M.createContext(rn),Br=["attr","size","title"];function Fr(t,a){if(t==null)return{};var n=zr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function zr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function ns(){return ns=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ns.apply(this,arguments)}function pt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function as(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?pt(Object(n),!0).forEach(function(r){Pr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pr(t,a,n){return a=Vr(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function Vr(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 on(t){return t&&t.map((a,n)=>M.createElement(a.tag,as({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Ur,ns({attr:as({},t.attr)},a),on(t.child))}function Ur(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=Fr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ns({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:as(as({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&M.createElement("title",null,l),t.children)};return xt!==void 0?M.createElement(xt.Consumer,null,n=>a(n)):a(rn)}function $r(t){return Me({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),o=s.useEditorStore(p=>p.card),l=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),h=M.useRef(),m=M.useRef({}),f=r.cards.find(p=>p.id===l),x=M.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);M.useEffect(()=>{if(l&&o.id&&o.id!==l){if(h.current&&c){const p=h.current.getModel();p&&(m.current[o.id]=p);let v=m.current[l];if(!v){const j=x();v=c.editor.createModel(j,t),m.current[l]=v}h.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,x]),M.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?p:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const p=h.current;p&&c&&o&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(p,v){if(h.current=p,!m.current[o.id]){const j=p.getModel(),b=x();m.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||p.getModel()}p.setModel(m.current[o.id])}return{handleEditorDidMount:g}}function qr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function l(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Hr({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function _s({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Fs(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=zs();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=zs(),c=s.useSelectedVisual(),i=nr(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Us(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ds(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:h,updateDataSource:m,clearQueryConfig:f,setCardConfig:x,setCardType:g}=s.useEditorActions();function p(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&m(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),x(void 0),d(""),u(""),h({}),g("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.sql}),d=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:m,setCardSql:f,setTempQueryData:x,setPythonStdOut:g,setCardPreferences:p,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:L,isError:k,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);m(P)}},[N,m,g]),M.useEffect(()=>{(D||w)&&S(!0),(k||L)&&S(!1),k&&(m([]),g(""))},[D,w,N,g,k,L,S,m,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),E(!1))},[R,I,E,A,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
406
+ */const je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Lt(c))}})}})}}function Lt(t){return{...t,customCfg:Ea(t.customCfg),data:[]}}function Ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ta(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Cs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ia(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:p}=s.useSemaphorContext();async function g(){d(!0);const x=Bs(h),v=await Ta(t,x,f,p==null?void 0:p.accessToken);v&&(l([...o||[],v]),c(v.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ma(){const[t,a]=M.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ia(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(p=>p.id!==m);o(f||[]),l("original")}}async function u(m){const h=n==null?void 0:n.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});o(h||[]);const f={...m,isDefault:!m.isDefault};await Cs(f,c==null?void 0:c.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==m.id){const g={...p,isDefault:!1};await Cs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(oa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function Rt(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ot(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const m=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=m;const f=`${o}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function La({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ot()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ct=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Ra(),[i,d]=M.useState(""),[u,m]=M.useState(ct[0].value),[h,f]=M.useState("06:00"),[p,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:x=>{g(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ct,value:u,onValueChange:x=>m(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:h,onChange:x=>f(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:u,time:h,subject:p}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(dt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(dt,{tooltip:`${x.endUserEmail}`,children:e.jsx(pa,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const dt=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Ra(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,l]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:u},{data:f,isLoading:p,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...D}=Rt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:p,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function cs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function Ft(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Oa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Fa=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Va=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ua=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Oa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Ka(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Fa((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Qa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>za((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Pa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>_a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Ya(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Va((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function Xa(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ua((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function Za(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>$a((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function er(t,a){return Za(ee.VISUAL,t,a)}function zt(){const[t,a]=M.useState(new Map),n=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=M.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Pt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Ka(t),c=Qa(t,a),i=Wa(t),d=Ja(),u=Ya(),m={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[m[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function sr(t,a){return Pt(ee.DASHBOARD,t,a)}function tr(t,a){return Pt(ee.VISUAL,t,a)}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ar({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var E;const{selectVisual:f}=s.useManagementActions(),p=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&p,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(ya,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function _t({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function es({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Vt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(l=>n(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function Ut({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function $t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function or(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ir({user:t}){return Gt(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function lr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=rr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(es,{currentRole:u,onRoleChange:h=>{l(t.id,a.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:xe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function ur({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var p,g;const m=((p=a.find(x=>x.id===d.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",f=xe(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,p;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((p=a.find(g=>g.id===i.tenantUserId))==null?void 0:p.type)||"",h=xe(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=xe(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(ir,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(es,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(lr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>p(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(dr,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const S=m.some(D=>D.id===E),N=h.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(ur,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(mr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?or(E,t,l):void 0,N=R.includes(E.id),D=!!S,w=D&&!N,L=m.some(A=>A.id===E.id),k=m.find(A=>A.id===E.id),O=r(E.type);return e.jsx(hr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:L,selectedUser:k,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(Se,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const De=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function xr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=De().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:m,f=a.role!=="NONE"&&!l&&(!o||o.newRole===m),p=o!==null&&o.newRole!==m,g=l,x=m==="NONE"||!m,v=b=>{switch(b){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ca,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!g&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Qt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,p=(x,v)=>{l(x,v)},g=()=>{c()};return e.jsx(xr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const pr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=fr(c),m=Xa(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function gr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var W,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:D}=we({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),k=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=f.some(Z=>Z.id===$),U=p.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const P=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(_t,{value:u,onChange:m}),e.jsx(Vt,{selectedUsers:f,selectedUserObjects:k,onRemove:O,onRoleChange:A,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx($t,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:De}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Qt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function ut({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:k,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=m.some(K=>K.id===G),te=h.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},T=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},P=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return p==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:p==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=D.filter(G=>m.some(Z=>Z.id===G.id)),q=L||O,U=k||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(at,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{value:i,onChange:u}),e.jsx(Vt,{selectedUsers:m,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:h,allUsers:D,onRemove:F}),e.jsx($t,{usersToUpdate:f,allUsers:D,onRemove:z,getRoleOptions:De}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:D,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Qt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Y,allUsersToUpdate:p==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||p==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||p==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(at,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),m=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function mt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const p=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,k,O,A;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!p||i==="specific_tenant_users"&&!p?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},D=()=>{var L,k,O,A;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const F={...T,updateAccess:!0};l(F)}}}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}},w=()=>{var L,k,O,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function jr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:p,isCurrentStateValid:g}=Wt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const E=d.length+u.length+m.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const E=f();E&&p(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&p(E)&&o(E)}else{const E=i.role;if(h===E){const N=f();if(N&&p(N)){const D={...N,removeAccess:!0};o(D)}}else{const N=f();if(N&&p(N)){const D={...N,updateAccess:!0};o(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,D,w,L;const{currentUser:d}=cs(),[u,m]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=M.useCallback(()=>{p.resetShareState(),l()},[p,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:k=>{const O=k;p.setSelectedTab(O),p.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(gr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(mt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(mt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(jr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Yt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m,tenantId:h}=t;if(u&&u.length>0){const f=Ce(n,r,u.map(p=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(m&&m.length>0&&m.forEach(f=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:h,role:f.newRole}]);o(p,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Xt(t,a,n,r){var u,m,h,f,p,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Ce(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(j){const b=Ce(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(j){const b=Ce(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(p=i==null?void 0:i.shares)==null?void 0:p.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function yr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Fs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Nr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function ht(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Cr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function Sr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Fs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:M.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=br(m),t(p));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Nr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function zs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=er((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a);return Cr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=M.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(h,C,"end"),c(!0),d(C.id),m(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:p,handleAddLibraryVisual:g,getUpdatedFrame:Sr().getUpdatedFrame,refetch:f.refetch}}function wr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[f,p]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=zs(),{resources:S,isLoading:N,isError:D,createResource:w,updateResource:L,deleteResource:k,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=tr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Y}=vr((m==null?void 0:m.id)||null,A,T);cs();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),p(!0)},U=()=>{g&&k(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=zt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{E(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{h(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ft,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(ar,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:B=>{!B&&y||(p(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var E;const{selectDashboard:f}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:o,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Dr({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Er(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[l,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,f]=M.useState(null),[p,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:D,updateResource:w,deleteResource:L,duplicateResource:k,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:F,removeResourceShares:z}=sr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=yr((h==null?void 0:h.id)||null,F,z),{currentUser:Y}=cs(),W=E.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&D({title:l,description:i,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),k(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=zt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=E.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{f(K),Y==null||Y.type,m(!0)};return we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ft,{}):N?e.jsx(Dr,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:l,onChange:K=>c(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:K=>d(K.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:K=>n(K.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ra,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(kr,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:c}=cs(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=qt(a,{enabled:t}),h=p=>{},f=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Er,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(wr,{})})]})})]})})}function Tr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,m]=M.useState(!1),h=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),x=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:D,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>D||w,[D,w]),k=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,F),C(F.id)},O=()=>{E(!0)};async function A(){if(m(!0),!r||!o)return;const T=Bs(l),F=JSON.stringify(T),z={...o,template:F,filterValues:p};await Cs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),m(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(La,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(Ma,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(It,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:h,onClose:()=>f(!1)})]})]})}function Ir({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ue.useRef(null),[h,f]=ue.useState(!1),[p,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{m.current&&g(m.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:p},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Tt,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ja,{className:"size-4"});if(t==="Table")return e.jsx(ls,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function p(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function g(){return e.jsx(Ir,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?p():g()})})}function Ar({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function p(x,v){var R;const j=s.createSqlGenConfig(x,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;m(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(h(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Ps({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Ue,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function xs({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Ps,{column:t}),e.jsx("span",{children:t.column_name})]})}function Mr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Lr({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(xs,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(xs,{column:a})}),e.jsx(Mr,{id:a.column_name,type:"column",children:e.jsx(xs,{column:a})})]})}const ps={id:"__placeholder__",role:"groupby",type:"string"},fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"metric",type:"number"},js={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Ee="droppable-group-by",Te="droppable-metrics",Ie="droppable-pivot-by",ss="sortable-group-by",Ss="sortable-metrics",ts="sortable-pivot-by",ws="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Rr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:T}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&T){const z=T.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==ps.id);q.splice($,0,ps),d(q)}else if(T.id===Ee){c(a.length);const $=[...a,ps];d($),u(n),m(r)}}if(Y||W){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==fs.id);q.splice($,0,fs),h(q)}else if(T.id===Ie){c(l.length);const $=[...l,fs];h($),d(a),u(n),m(r)}}if(P||Y){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==gs.id);q.splice($,0,gs),u(q)}else if(T.id===Te){c(n.length);const $=[...n,gs];u($),m(r),d(a),h(l)}}if(S(_)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==js.id);q.splice($,0,js),m(q)}else if(T.id===ws){c(r.length);const $=[...r,js];m($),u(n),d(a),h(l)}}}else d(a),u(n),m(r),h(l)};function E(I){i(I.active.id),c(null),d(a),u(n),m(r),h(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:pe(T),name:T,label:He(T,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),p(z)}function D(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],F=t!==null?t:l.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,F),g(y)}function k(I){var z,_,P,Y,W,V,$,q;const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(T.id===Ee||((z=T.data.current)==null?void 0:z.type)===ss)&&w(U),(Q||G)&&(T.id===Ie||((_=T.data.current)==null?void 0:_.type)===ts)?D(U):(H||Q)&&(T.id===Te||((P=T.data.current)==null?void 0:P.type)===Ss)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===ws||((Y=T.data.current)==null?void 0:Y.type)===ks)&&L(U)}if(T&&((W=T.data.current)==null?void 0:W.type)===ss&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(T&&((V=T.data.current)==null?void 0:V.type)===ts&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),H=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...l],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===Ss&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),i(null),c(null),d(a),u(n),m(r),h(l)}function O(I){const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)===_s&&T){const z=o.findIndex(P=>Ve(P.columnId)===y.id),_=o.findIndex(P=>Ve(P.columnId)===T.id);if(z!==-1&&_!==-1&&z!==_){const P=[...o],[Y]=P.splice(z,1);P.splice(_,0,Y),x(P)}}}function A(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:k,handleDragStart:E,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${_s}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Or({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),m=s.useEditorStore(y=>y.selectedTableName),h=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function D(y){var T;if(l){const F=s.createSqlGenConfig(y,o);C(F);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",E,d||"");_&&(j(_),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(m||N)&&c?(p({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===m||y.datamodelName===N)))!==void 0}function A(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Lr,{onClick:D,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(xa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:m,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:k,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Or,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":k?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),h(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:F,showNone:!0,onChange:$,isError:D,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!T&&(!c||c==="none")&&(!l||l==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:W,items:p,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(fa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const p=f.toString();navigator.clipboard.writeText(p),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(la,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},xt=M.createContext&&M.createContext(rn),Br=["attr","size","title"];function Fr(t,a){if(t==null)return{};var n=zr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function zr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function ns(){return ns=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ns.apply(this,arguments)}function pt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function as(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?pt(Object(n),!0).forEach(function(r){Pr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pr(t,a,n){return a=_r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function _r(t){var a=Vr(t,"string");return typeof a=="symbol"?a:a+""}function Vr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function on(t){return t&&t.map((a,n)=>M.createElement(a.tag,as({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Ur,ns({attr:as({},t.attr)},a),on(t.child))}function Ur(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=Fr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ns({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:as(as({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&M.createElement("title",null,l),t.children)};return xt!==void 0?M.createElement(xt.Consumer,null,n=>a(n)):a(rn)}function $r(t){return Me({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),f=r.cards.find(x=>x.id===l),p=M.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);M.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let v=h.current[l];if(!v){const j=p();v=c.editor.createModel(j,t),h.current[l]=v}m.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,p]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(x,v){if(m.current=x,!h.current[o.id]){const j=x.getModel(),b=p();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function qr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function l(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Hr({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Vs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Fs(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=zs();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=zs(),c=s.useSelectedVisual(),i=nr(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Us(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ds(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:p,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),p(void 0),d(""),u(""),m({}),g("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.sql}),d=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:L,isError:k,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);h(P)}},[N,h,g]),M.useEffect(()=>{(D||w)&&S(!0),(k||L)&&S(!1),k&&(h([]),g(""))},[D,w,N,g,k,L,S,h,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),E(!1))},[R,I,E,A,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
407
407
 
408
408
  Error:
409
409
 
@@ -415,11 +415,11 @@
415
415
 
416
416
  ${d?`Python:
417
417
  ${d}`:""}
418
- `;b(P)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Hr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function z(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(qr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function 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||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[D||w?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(an,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:T}),e.jsx(ds,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx($r,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{}),e.jsx(_s,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[z(),F()]}),V()]})}function Wr({data:t}){var c;const[a,n]=M.useState([]),o=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),l=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:l.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=l.getRowModel().rows)!=null&&c.length?l.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Jr({card:t}){var b,C,R,E,S,N,D,w,L,k,O;const[a,n]=M.useState(!1),[r,o]=M.useState([]),{authToken:l}=s.useSemaphorContext(),c=s.getTokenParams(l==null?void 0:l.accessToken),i=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((E=t.customCardPreferences)==null?void 0:E.url)||""),h=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",m=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:x}=s.useDashboardCardQuery(t),g=M.useCallback((A,I)=>{o(y=>({...y,[A]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const p=u((D=t.customCardPreferences)==null?void 0:D.componentName);function v(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=m==null?void 0:m.cards)==null?void 0:z.find(V=>V.id===I);return y||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&h==="single"&&e.jsx(p,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(x==null?void 0:x.records)||[]}),p&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=m==null?void 0:m.cards)==null?void 0:z.find(V=>V.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:d,onDataChange:g,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function cn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,l=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===l.filterId),{data:u,isLoading:h,isFetching:m,errorMessage:f}=s.useDashboardCardQuery(n),{setCard:x}=s.useEditorActions(),{data:g}=s.useTopoJson(n),p=M.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackCustomVisual,children:e.jsx(Jr,{card:C})})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!h&&!m)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&p)return e.jsx(e.Fragment,{children:h||m?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:p})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>x({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>x({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>i({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const ys=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),Yr=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Xr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{language:"javascript",value:t,onChange:o})})]}),Zr=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function eo(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(""),h=s.useEditorStore(E=>E.card),m=s.useEditorStore(E=>E.card.customCfg),f=m?JSON.stringify(m,null,2):"",{data:x}=s.useDashboardCardQuery(h),{data:g}=s.useTopoJson(h),{setCardCustomCfg:p,setCustomVisualCode:v}=s.useEditorActions(),j=E=>{var S,N;return JSON.stringify({...E,data:{...E.data,datasets:(N=(S=E.data)==null?void 0:S.datasets)==null?void 0:N.map(D=>({...D,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=x==null?void 0:x.records)!=null&&S.length))return;const E=s.createChartConfig({card:h,data:x.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:g});if(E){r(j(E)),i(((N=h.preferences)==null?void 0:N.customVisualCode)||"");const D=s.merge(E,m);l(j(D))}},C=()=>{try{if(c&&v(c),o){const E=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),E);p(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Yr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Xr,{customCode:c,cardCustomCfgString:f,mergedConfig:o,onConfigChange:E=>l(E??""),onCodeChange:E=>i(E??"")})]}),e.jsx(Zr,{error:d,hasCardCustomConfig:!!m,onReset:()=>{l(n),p(null)},onApply:C,onClose:()=>a(!1)})]})]})}function us(t){const[a,n]=M.useState(null);return a}function $s(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function so({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:l,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=$s();function d(u,h){r(null),o({}),l(u),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(i){const f=(await Promise.all((h=i==null?void 0:i.plugins)==null?void 0:h.map(async x=>(await s.loadManifest(x.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:x.value}))))).flat();n(f)}})()},[i]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((u,h)=>e.jsx(to,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+h))})]})}const to=({text:t,icon:a,onClick:n})=>{const r=us(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function qs(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function no(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function Gs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Hs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Ks(t){return Me({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Qs(t){return Me({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function dn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:l,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(h,m){l(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Ct,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})})]})}function ao({chartType:t,className:a,customIcon:n,componentName:r}){const o=us();switch(t){case"bar":return e.jsx(rs,{className:a});case"line":return e.jsx(os,{className:a});case"pie":return e.jsx(is,{className:a});case"radar":return e.jsx(Rs,{className:a});case"scatter":return e.jsx(As,{className:a});case"bubble":return e.jsx(Gs,{className:a});case"doughnut":return e.jsx(Ms,{className:a});case"stackedBar":return e.jsx(Ts,{className:a});case"stackedLine":return e.jsx(Ks,{className:a});case"polarArea":return e.jsx(qs,{className:a});case"funnel":return e.jsx(Hs,{className:a});case"tornado":case"pyramid":return e.jsx(Os,{className:a});case"range":return e.jsx(Is,{className:a});case"kpi":return e.jsx(Qs,{className:a});case"text":return e.jsx(Ge,{className:a});case"map":return e.jsx(Ls,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx($e,{className:a});default:return e.jsx(ls,{className:a})}}function un({variant:t="ghost"}){var l,c;const[a,n]=M.useState(!1),r=s.useEditorStore(i=>i.card),o=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(ao,{className:"size-4",chartType:o,customIcon:(l=r.customCardPreferences)==null?void 0:l.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(dn,{onChartTypeChange:()=>n(!1)}),e.jsx(so,{onChartTypeChange:()=>n(!1)})]})]})}const Ke="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function ft(t,a){var r,o,l;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((l=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:l.type)||"linear"}function ro(){var T,F,z,V,P,Y;const[t,a]=M.useState(!1),n=s.useEditorStore(W=>{var _;return(_=W.card)==null?void 0:_.preferences}),r=s.useEditorStore(W=>{var _;return(_=W.card)==null?void 0:_.type}),o=s.getNumberAxis(n,{}),[l,c]=M.useState(ft(n,r)),[i,d]=M.useState(((z=(F=(T=n==null?void 0:n.chartOptions)==null?void 0:T.scales)==null?void 0:F[o])==null?void 0:z.min)||""),[u,h]=M.useState(((Y=(P=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:P[o])==null?void 0:Y.max)||""),[m,f]=M.useState(i||u?"custom":"auto"),[x,g]=M.useState(""),[p,v]=M.useState(0),[j,b]=M.useState(""),[C,R]=M.useState(""),[E,S]=M.useState(""),N=s.useEditorStore(W=>W.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),w=s.useEditorStore(W=>W.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var W,_,$,q,U,H,Q,G,Z,te,ae,se,oe,K;c(ft(n,r)),d((($=(_=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:_[o])==null?void 0:$.min)===0?0:""),h(((H=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:H.max)||""),g(((te=(Z=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,o,r]);function k(W,_){return _===""||/^[0-9\b]+$/.test(_)?Number(_):Number(W)}function O(){const W=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(_=>_.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:_=>R(_==="none"?"":_),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),W.map(_=>e.jsx(s.SelectItem,{value:_,children:_},_))]})})]}),e.jsxs(s.Select,{value:E,onValueChange:_=>S(_),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(_=>e.jsx(s.SelectItem,{value:_.locale,children:_.locale},_.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:p,onChange:_=>v(Number(_.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ke}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:l,onValueChange:W=>c(W),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),l=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:m,onValueChange:W=>f(W),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),m==="custom"&&l=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:W=>d(_=>k(_,W.target.value)),className:`col-span-1 h-8 w-full ${Ke}`}),e.jsx(s.Input,{value:u,onChange:W=>h(_=>k(_,W.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ke}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:x,onChange:W=>g(_=>k(_,W.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ke}`})]})]})}function y(){var q;let W={};m==="custom"&&(W={min:i,max:u,ticks:{stepSize:x}});const _={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:l,...l==="linear"?W:{}}}},numberAxisFormat:{decimalPlaces:p,suffix:j,currency:C,locale:E}};console.log(_),N(_);const $={...w,preferences:_};D($)}return e.jsxs(s.Popover,{onOpenChange:W=>a(W),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(Zn,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function oo(){const t=s.useEditorStore(i=>{var d,u,h,m;return(m=(h=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.position}),a=s.useEditorStore(i=>{var d,u,h,m;return(m=(h=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.align}),n=s.useEditorStore(i=>{var d,u,h,m;return(m=(h=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:h.legend)==null?void 0:m.display}),{setLegendOptions:r}=s.useEditorActions(),o=i=>{r({display:i,position:t,align:a})},l=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(da,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>l("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>l("left"),children:e.jsx(Vn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>l("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>l("right"),children:e.jsx(_n,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(On,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Rn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Bn,{className:"size-4"})})]})]})]})]})]})})]})}function io(){const t=s.useEditorStore(l=>{var c,i;return(i=(c=l.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(l=>l.card.type),{setChartOrientation:n}=s.useEditorStore(l=>l.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function mn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function l(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(io,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ro,{}),e.jsx(oo,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(r==="xy"||!r)&&e.jsx(ia,{className:"size-4"}),r==="x"&&e.jsx(Jn,{className:"size-4"}),r==="y"&&e.jsx(ba,{className:"size-4"}),r==="none"&&e.jsx(ka,{className:"size-4"})]})]}):null}function lo(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:l}=s.useEditorActions(),c=(g,p)=>{g.dataTransfer.setData("tabIndex",p.toString())},i=g=>{g.preventDefault()},d=(g,p)=>{const v=g.dataTransfer.getData("tabIndex");if(v===p.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(p,0,b),n({...t,cards:j})};function u(g){const p=t.cards.filter(b=>b.id!==g),v=p[0],j={...t,cards:p,activeCardId:v.id};n(j),r(v.id),o(v)}function h(g,p){const v={...t,cards:[...t.cards,p],activeCardId:g.id};n(v),r(p.id)}function m(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,g)}function f(g){const p={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(g,p)}function x(g,p){return g.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||g.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=p.displayTab===void 0?!1:!p.displayTab;o({...p,displayTab:v}),l({...p,displayTab:v})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ea,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((g,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,p),onDragOver:i,onDrop:v=>d(v,p),className:"",value:g.id,children:[x(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),l({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:m,children:e.jsx(Xn,{className:"h-4 w-4"})})]})})}function hn(){const t=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:o,setActiveTabCardId:l,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:h,isFetching:m}=s.useDashboardCardQuery(a);function f(p){const v=t.cards.find(j=>j.id===p);if(v!=null&&v.sql){r||i(!0),l(p);return}if(v!=null&&v.queryConfig){r&&i(!1),x(p),l(p);return}r||x(p),l(p)}function x(p){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:p};o(v);const j=v.cards.find(b=>b.id===p);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:g()},p.id)),e.jsx(lo,{})]})}function Qe({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),l=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:h}=s.useEditorActions(),{data:m,isLoading:f,isFetching:x,errorMessage:g}=s.useDashboardCardQuery(a);function p(){const b=JSON.stringify(m==null?void 0:m.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),E=document.createElement("a");E.href=R,E.download=`${a.title}.json`,E.click()}function v(){const C=[Object.keys(m==null?void 0:m.records.reduce((N,D)=>({...N,...D}),{})).join(","),...((m==null?void 0:m.records)||[]).map(N=>Object.values(N).join(","))].join(`
419
- `),R=new Blob([C],{type:"text/csv"}),E=URL.createObjectURL(R),S=document.createElement("a");S.href=E,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(f||x)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(un,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Gn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(eo,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(no,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(ta,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(mn,{})]}),n&&e.jsx(uo,{})]}),r?e.jsx(hn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:l&&e.jsx(co,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(Wr,{data:(m==null?void 0:m.records)||[]}),g&&e.jsx(tn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function co(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function uo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function mo(){var p,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=$s(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(j=>j.name===(t==null?void 0:t.componentName));function h(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function m(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(E=>{var S;return((S=E==null?void 0:E.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((E,S)=>{var N,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((D=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:D.cardId)||"",onValueChange:w=>h(S,w)})]},S+Math.random())})})}function f(j,b,C=[],R=""){var E,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function x(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(qn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:g,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(he,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(j=>j.type===l).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:m(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:x(u)})})]})]})]})}function Le(){const[t,a]=M.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var h;return(h=u.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function c(u,h){var m,f;h?n!=null&&n.onClickFilter&&((m=n==null?void 0:n.onClickFilter)==null?void 0:m.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(x=>x.columnIndex!==u)}),a(x=>{const g=[...x];return g[u]=!1,g}))}function i(u,h){var f;const m=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(x=>x.columnIndex===u?{...x,expression:h.target.value}:x);o({...n,onClickFilter:m})}function d(u){var h,m,f,x;if(t!=null&&t[u]||(m=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))!=null&&m.expression)return e.jsx(s.Input,{value:(x=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))==null?void 0:x.expression,onChange:g=>i(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),l==null?void 0:l.map((u,h)=>{var m,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((m=n==null?void 0:n.onClickFilter)!=null&&m.find(x=>x.columnIndex===h)),onCheckedChange:x=>c(h,x)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(x=>x.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(x=>{const g=[...x];return g[h]=!x[h],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},u)})]})}function ho({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,l=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:h}]});else{const m={...l};m.datalabels=h;const f=n==null?void 0:n.map(x=>x.idx===u?m:x);r({...a,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Mt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ua,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ha,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ma,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function xo(){const t=s.useEditorStore(l=>l.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ws({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function xn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,h,m;return(m=(h=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:h.chartOptions)==null?void 0:m.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=xo();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:pn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(fn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function pn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function fn({col:t,idx:a,className:n,iconClassName:r,children:o}){const l=s.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),c=s.useEditorStore(h=>{var m,f;return(f=(m=h.card)==null?void 0:m.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function u(h){if(!i)d({...l,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const m={...i};m.type=h==="area"?"line":h,m.fill=h==="area"?"origin":"";const f=c==null?void 0:c.map(x=>x.idx===a?m:x);d({...l,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ws,{className:"max-w-[100px]",title:t,children:pn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(rs,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(os,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(wt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ho,{idx:a})]})]})}function gn(){const t=s.useEditorStore(x=>x.selectedConnectionId),a=s.useEditorStore(x=>x.selectedDatamodelId),n=s.useEditorStore(x=>x.selectedDatabaseName),r=s.useEditorStore(x=>x.selectedSchemaName),o=s.useEditorStore(x=>x.selectedTableName),l=s.useDashboardStore(x=>x.dashboard.filters)||[],c=s.useDashboardStore(x=>x.actions.addFilter),i=s.useDashboardStore(x=>x.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:h,connectionType:m}=s.useEditorAside();function f(x,g="dashboard"){var N;const p=s.fmt(x.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(h);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:m,databaseName:v}),R=`${C}.${p}`;const E=(N=u==null?void 0:u.find(D=>D.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${E}.${p}`,C=`${s.DATAMODEL_NAMESPCACE}.${E}`);const S=l==null?void 0:l.find(D=>D.column===R&&D.table===b&&(D.database===v||D.database===n));if(S)d(S.id),i(S.id);else{const D=s.v4();return h==="api"&&t?(c({location:g,id:D,column:R,title:x.column_name,dataType:x.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(x.data_type,C,p)}),D):(c({id:D,location:g,column:R,title:x.column_name,dataType:x.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(x.data_type,C,p)}),D)}}return{assignFilter:f}}function Ve(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();function l(i){const d=o(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(po,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function po({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,l]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===o?"":d;l(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function fo({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(xn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Ve,{})]})]})]})})}function ms(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var h;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?l():c()})}function go({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(ms,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Ve,{})]})]})]})})}const jo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},yo={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function vo(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:bo(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ms,{}),e.jsx(Le,{}),e.jsx(Ve,{})]})]})}function bo(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(jo,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(yo,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function No(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function vs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Co=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],So=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],wo=So.map(t=>({label:t,value:t}));function ko(){var d,u,h,m,f,x,g,p,v,j,b,C,R,E,S,N,D,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=M.useState(((m=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(L=>({label:L,value:L}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(vs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(vs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((x=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:x.objectKey)||"",label:"Map Object",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Co,value:((p=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:wo,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(vs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(E=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(D=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Do(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function We({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[t!=="text"&&e.jsx(ms,{}),t==="text"&&e.jsx(Do,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Ve,{})]})]})]})})}function Eo(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(xn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Ve,{})]})]})]})})}function To({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Ve,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const Io=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ao=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Mo=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Lo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Eo,{});case"tornado":case"pyramid":return e.jsx(We,{docContent:Io,cardType:n});case"kpi":return e.jsx(No,{});case"line":case"bar":return e.jsx(fo,{cardType:n});case"range":return e.jsx(We,{docContent:Ao,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(We,{cardType:n});case"bubble":case"scatter":return e.jsx(go,{cardType:n});case"table":return e.jsx(To,{cardType:n});case"text":return e.jsx(We,{docContent:Mo,cardType:n,suffix:"Visual"});case"map":return e.jsx(ko,{});case"custom":return e.jsx(mo,{});default:return e.jsx(vo,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function jn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function l(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Ro=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ue,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Pn,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Oo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Ro;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};a(t.id,l)}return e.jsx(jn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Bo=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Fo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:Pe(t.name,r)};a(t.id,o)}return e.jsx(jn,{column:t,functions:Bo,onFunctionChange:r=>n(r),label:"Granularity"})}function zo({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=M.useMemo(()=>{let i=[];(n===Ee||n===Te||n===Ie)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var h;return u.column_name===((h=i[0])==null?void 0:h.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function yn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,h;return(h=(u=d.card)==null?void 0:u.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(fn,{idx:l,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(ms,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Po({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,l]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:h,setNodeRef:m,transform:f,transition:x,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),p=f?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(f),transition:x}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),D=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":D?"string":w?"date":"string";if(r===Ee){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,role:"groupby",label:Pe(S.column_name,"month"),granularity:"month"};c(t.id,k)}}if(r===Ie){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,label:Pe(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,k)}}if(r===Te){const k={id:t.id,name:S.column_name,type:L,role:"metric",label:He(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};i(t.id,k)}}function b(){if(r===Te)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(yn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Te)return e.jsx(Oo,{column:t});if((r===Ee||r===Ie)&&S)return e.jsx(Fo,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ee||r===Ie)&&v}),children:e.jsx(zo,{col:t,onChange:j,droppableId:r})})}function E(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>l(!o),children:o?e.jsx(Sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Dt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...u,ref:m,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[E(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function bs({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:l}){var p,v;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),h=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),m=i||((v=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:v.type)===o,f=u?r:n,x=o===ss?"Rows":o===ts?"Pivot Columns":"Columns";function g(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",m&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:x})]}),g(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(j=>j.id===en.id?e.jsx(Vo,{},j.id):e.jsx(Po,{droppableId:t,type:o,column:j,onRemoveColumn:l},j.id))})]})})}function Vo(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function vn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function _o(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function f(j,b){const C=x(j);return C?C.role==="metric"?b==="asc"?u:h:b==="asc"?i:d:null}function x(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};l(C)}}const p=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>_e(j.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),m.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:m,selectedOptions:[],onChange:j=>p(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(vn,{id:_e(j.columnId),type:Vs,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Dt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ws,{className:"w-[175px] text-sm",children:((b=x(j.columnId))==null?void 0:b.label)||((C=x(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:f(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},j.columnId)},_e(j.columnId))})]})})}function Uo(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),l=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function h(v){i(v)}function m(v){d(v)}function f(v){u(v)}let x="Group By",g="Metrics",p="Stack By";return a==="table"&&(x="Rows",g="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(dn,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(bs,{onRemoveColumn:h,sortableType:ss,id:Ee,label:x,columns:t,previewColumns:n}),e.jsx(bs,{onRemoveColumn:f,sortableType:ts,id:Ie,label:p,columns:l,previewColumns:c}),e.jsx(bs,{onRemoveColumn:m,sortableType:Ss,id:Te,label:g,columns:r,previewColumns:o}),e.jsx(_o,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Js({children:t,column:a,id:n,sortableType:r,className:o}){const[l,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(m=>{var f,x;return(x=(f=m.card.queryConfig)==null?void 0:f.filters)==null?void 0:x.some(g=>g.filterColumnName===a.name)});function h(m){i(m)}return e.jsx(vn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>h(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!l&&"rounded-b-md",l&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function $o({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,E;return(E=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:E.filters}),o=s.useEditorStore(C=>{var R,E;return(E=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:E.find(S=>S.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),m={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:f,isLoading:x,isFetching:g,isError:p}=s.useFilterQuery(m),v=M.useMemo(()=>{var R;return m.column?(R=f==null?void 0:f.records)==null?void 0:R.map(E=>{let S=m.column.split(".").slice(-1)[0].replace(/"/g,"");return E[S]===void 0&&(S=S.toLowerCase()),{id:E[S],value:E[S]}}):[]},[f,m.column]);function j(C){const R=C.map(E=>E.id);h(t.name,R)}function b(){return x||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(qo,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Js,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function qo({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Go({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:h,data:m}=s.useFilterQuery(i),f=m==null?void 0:m.records,{dateRange:x,setDateRange:g,initialDateRange:p}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const E={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,E)}function b(){v(t.name,null,!0),g(p)}function C(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:x,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Js,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Ho({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,p;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},h=c||((p=(g=i==null?void 0:i.data)==null?void 0:g.current)==null?void 0:p.type)===o;function m(){if(!x||x.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(v){const j=s.isDateDataType(v.type);return v.id===en.id?e.jsx(Js,{id:v.id,sortableType:o,column:v,children:e.jsx(Ko,{})},v.id):j?e.jsx(Go,{droppableId:t,sortableType:o,column:v},v.id):e.jsx($o,{droppableId:t,sortableType:o,column:v},v.id)}const x=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),m(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:x==null?void 0:x.map(v=>f(v))})]})})}function Ko(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Qo(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Ho,{onRemoveColumn:r,sortableType:ks,id:ws,label:"Filters",columns:t,previewColumns:a})})}function Wo(){const t=s.useEditorStore(l=>l.card),a=s.useEditorStore(l=>l.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ds,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(an,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Us,{}),e.jsx(_s,{variant:"default"})]})]})}function Jo(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,u,h;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(h=a.current)==null||h.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Lo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Qe,{})})]}):e.jsx(Qe,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Uo,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(Wo,{}),e.jsx(Qo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Qe,{})})]})})]}):e.jsx(Qe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?l():c()})}function Yo(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[o,l]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.sql}),d=s.useEditorStore(B=>B.isDevMode),u=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.python}),{setCardPython:h,setCardSql:m,setRunSql:f,switchCardType:x,setQueryConfig:g}=s.useEditorActions(),p=s.useEditorStore(B=>B.currentAssitantScope)||[],v=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),R=s.useEditorStore(B=>B.selectedTableName),E=s.useEditorStore(B=>B.selectedConnectionId),S=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:D,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:k,setCurrentAssitantScope:O,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:T}=s.useEditorAside(),{messages:F,setMessages:z,reload:V,error:P,append:Y,input:W,setInput:_,status:$,handleInputChange:q,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:Q,onFinish(B,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&v&&(Y({role:"user",content:v}),k(!1))},[j,v,Y,k]);async function Q({toolCall:B}){var J,ie,ye,ke;if(["createChartFromSql","createForecast"].includes(B.toolName)){const ne=B.args.sql,le=B.args.python,ce=B.args.chartType;return x(ce),m(ne),h(le),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:u||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:p};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const ne=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,x(ne),A(le),m(void 0),h(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(ye=ce==null?void 0:ce.data)!=null&&ye.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(ke=ce==null?void 0:ce.data)==null?void 0:ke.records}}else r("Analyzing...")}}function G(B){l(J=>J?{promptTokens:J.promptTokens+B.promptTokens,completionTokens:J.completionTokens+B.completionTokens,totalTokens:J.totalTokens+B.totalTokens}:B)}function Z(B){const J=s.removeFromScopeArray(p,B);te(J)}function te(B){const J=s.sanitizeAIScope(B);O(J),z(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:T||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||""},J=s.dedup([...p,B]);te(J)}function se(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||"",datamodelId:T||""};if(!s.isInAiScopeArray([...N||[],...p],B)||p.length===0){const ie=s.dedup([...N||[],...p,B]).filter(ye=>ye.connectionId===B.connectionId);te(ie)}}const oe=!["ready","error"].includes($),K=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:V,append:Y,input:W,setInput:_,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:p,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:H,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:K}}const Xo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function gt(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[o,l]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,u]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),f=s.useDashboardStore(H=>H.dashboard.aiContext),x=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),p=s.useEditorStore(H=>H.actions.setRunSql),v=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:D,append:w,input:L,setInput:k,isLoading:O,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:T,llmUsage:F,errorMessage:z}=Yo();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),M.useEffect(()=>{var H;v&&((H=a.current)==null||H.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[v,x,m]);function V(H,Q){Q==="sql"?(g(H),p(!0)):Q==="python"&&(C(H),p(!0))}function P(){var H;(H=f==null?void 0:f.selectedEntities)==null||H[0],u(!0)}function Y(){h.selectedEntities.length===0&&m({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function W(H){Y();const Q={role:"user",content:H.title+" "+H.subtitle};w(Q)}function _(H){Y(),w({role:"user",content:H})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:T,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!E&&e.jsx(s.Placeholders,{onClick:W,placeholders:Xo}),e.jsx("div",{children:U&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:_})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:k,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Y(),I(H)},isLoading:O,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:d,onOpenChange:u,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function bn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const l=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return l===t&&c===a||l===a&&c===t})}function Zo(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!bn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function Ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Es(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Ys=t=>{var k;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),h=s.useEditorStore(O=>O.card.type),m=t==null?void 0:t.id,f=M.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),x=M.useCallback((O,A)=>{if(m)switch(O){case"groupBy":{a(m,{groupByColumns:A});break}case"metrics":{a(m,{metricColumns:A});break}case"pivotBy":{a(m,{pivotByColumns:A});break}case"sortBy":{a(m,{sortByColumns:A});break}}},[m,a]),g=M.useCallback((O,A,I)=>{if(!m)return;const T=f(O)[A];if(T)switch(O){case"groupBy":n(m,T.id,{label:I});break;case"metrics":r(m,T.id,{label:I});break;case"pivotBy":o(m,T.id,{label:I});break;case"sortBy":l(m,T.id,{label:I});break}},[m,f,n,r,o,l]),p=M.useCallback((O,A)=>{if(!m)return;const y=f("metrics")[O];y&&r(m,y.id,{aggregate:A,label:s.getAggregationLabel(y.name,A)})},[m,f,r]),v=M.useCallback((O,A,I)=>{if(!m)return;const T=f("groupBy")[O];if(!T)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(m,T.id,F)},[m,f,n]),j=M.useCallback((O,A)=>{if(!m)return;const y=f("groupBy")[O];y&&n(m,y.id,{granularity:A})},[m,f,n]),b=M.useCallback((O,A)=>{if(!m)return;const y=f("metrics")[O];y&&r(m,y.id,{aliasTemplate:A})},[m,f,r]),C=M.useCallback((O,A)=>{if(console.log("handleValueAliasesChange",O,A),!m)return;console.log("handleValueAliasesChange",O,A);const y=f("metrics")[O];y&&(console.log("handleValueAliasesChange",A),r(m,y.id,{valueAliases:A}))},[m,f,r]),R=M.useCallback(O=>{m&&a(m,{comparisonType:O})},[m,a]),E=M.useCallback(O=>{m&&a(m,{showTrendline:O})},[m,a]),S=M.useCallback(O=>{m&&a(m,{trendlineWindow:O})},[m,a]),N=M.useCallback(O=>{m&&a(m,{trendlineGranularity:O})},[m,a]),D=M.useCallback(O=>{m&&a(m,{targetValue:O})},[m,a]),w=M.useCallback(O=>{var V;if(!m)return;const A=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,y=Zo(O,A,I);if(!y.isValid){y.showError&&Ds();return}const T=s.getSmartContainerForField(O),F=f(T);if(Es(O,F))return;const z=s.getNewField(O,T);z&&x(T,[...F,z])},[m,(k=t==null?void 0:t.config)==null?void 0:k.joinPlan,f,x]),L=M.useCallback((O,A)=>{if(!m)return;const y=f(O)[A];if(y){if(O!=="sortBy"){const T=f("sortBy"),F=T.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==T.length&&a(m,{sortByColumns:F})}switch(O){case"groupBy":c(m,y.id);break;case"metrics":i(m,y.id);break;case"pivotBy":d(m,y.id);break;case"sortBy":u(m,y.id);break}}},[m,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:x,updateLabel:g,handleAggregationChange:p,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:D,cardType:h}};function ei({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function si({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),u=s.useEditorStore(g=>g.card),{handleFieldClick:h}=Ys(u),m={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const f=g=>{const p=(g||"").toLowerCase();switch(s.getDataType(p)){case"number":return Ue;case"date":return s.Calendar;case"boolean":return Ze;case"json":return rt;case"geo":return ot;default:return Ge}},x=g=>{const p=(g||"").toLowerCase(),v=s.getDataType(p);return v==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):v==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):v==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):v==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):v==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(rt,{className:"h-3 w-3"})}):v==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ot,{className:"h-3 w-3"})}):v==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(St,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:m,...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:()=>h(t),children:[x(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ei,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function ti(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(C=>h(C)===n)).reduce((C,R)=>{const E=R.qualifiedEntityName||"Other Fields";return C[E]||(C[E]={label:s.toLabel(R.entityName),fields:[]}),C[E].fields.push(R),C},{}),g=Object.keys(f),p=u.filter(C=>h(C)==="dimensions").length,v=u.filter(C=>h(C)==="metrics").length,j=u.filter(C=>h(C)==="calculated").length,b=u.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[l.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(St,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(f).map(([C,R])=>{const E=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:E.label||E.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(S=>e.jsx(si,{field:S},S.id))})})]},C)})}),Object.keys(f).length===0&&l.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&l.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function ni(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ti,{})," "]})}function ai({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[o,l]=M.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,N={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,N]}),l(new Set([...o,N.id]))},i=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),l(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var k,O;const D=n.joins.find(A=>A.id===S);if(!D)return;const w={...D,...N},L=n.joins.map(A=>A.id===S?w:A);if((k=w.source)!=null&&k.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},T=[...w.joinKeyGroups];T[0]={...T[0],keys:[y]},w.joinKeyGroups=T,L[L.findIndex(F=>F.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N>0){const D=[...n.joins],w={...D[N]},L={...D[N-1]};D[N]=L,D[N-1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},moveJoinDown:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N<n.joins.length-1){const D=[...n.joins],w={...D[N]},L={...D[N+1]};D[N]=L,D[N+1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),l(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{D.add(w.source.name),D.add(w.target.name)}),a.filter(w=>D.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const D=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:D})},updateGroupOperator:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:D},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const D=n.joins.find(L=>L.id===S);if(!D)return;const w=[...D.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const D=n.joins.find(A=>A.id===S);if(!D)return;const w=a.find(A=>A.name===D.source.name),L=a.find(A=>A.name===D.target.name),k=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};k[N]={...k[N],keys:[...k[N].keys,O]},d(S,{joinKeyGroups:k})},updateJoinKey:(S,N,D,w,L)=>{const k=n.joins.find(T=>T.id===S);if(!k)return;const O=a.find(T=>T.name===k.source.name),A=a.find(T=>T.name===k.target.name),I=[...k.joinKeyGroups],y=I[N].keys[D];w==="sourceColumnName"&&O?I[N].keys[D]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[N].keys[D]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[D]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(D,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
420
- FROM ${N.name}`;return S.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const k=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var T,F,z,V;return((T=y.source)==null?void 0:T.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((V=y.target)==null?void 0:V.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),O=k.length>1?k.join(" OR "):k[0]||"condition_here";D+=`
418
+ `;b(P)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Hr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function z(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(qr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:D||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[D||w?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(an,{sql:N==null?void 0:N.sql,error:y,onDebugWithAssistant:T}),e.jsx(ds,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx($r,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{}),e.jsx(Vs,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[z(),F()]}),_()]})}function Wr({data:t}){var c;const[a,n]=M.useState([]),o=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const u=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,u==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):u==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),l=s.useReactTable({data:t,columns:o,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:l.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=l.getRowModel().rows)!=null&&c.length?l.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Jr({card:t}){var b,C,R,E,S,N,D,w,L,k,O;const[a,n]=M.useState(!1),[r,o]=M.useState([]),{authToken:l}=s.useSemaphorContext(),c=s.getTokenParams(l==null?void 0:l.accessToken),i=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:C.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((E=t.customCardPreferences)==null?void 0:E.url)||""),m=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:p}=s.useDashboardCardQuery(t),g=M.useCallback((A,I)=>{o(y=>({...y,[A]:I}))},[]);if(!((N=t.customCardPreferences)!=null&&N.componentName))return null;const x=u((D=t.customCardPreferences)==null?void 0:D.componentName);function v(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(_=>_.id===I);return y||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:g,data:(p==null?void 0:p.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((k=t.customCardPreferences)==null?void 0:k.dataInputCardIds)||{}).map(A=>{var T,F,z;const I=(F=(T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=h==null?void 0:h.cards)==null?void 0:z.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:g,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function cn({className:t,...a}){var b;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),o=((b=n.customCardPreferences)==null?void 0:b.showCardHeader)??!0,l=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===l.filterId),{data:u,isLoading:m,isFetching:h,errorMessage:f}=s.useDashboardCardQuery(n),{setCard:p}=s.useEditorActions(),{data:g}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(u!=null&&u.records)?null:s.createChartConfig({card:n,data:u==null?void 0:u.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,u==null?void 0:u.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function v(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackCustomVisual,children:e.jsx(Jr,{card:C})})}function j(){if(u!=null&&u.records&&(u==null?void 0:u.records.length)===0&&!m&&!h)return f?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return v(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:m||h?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(u!=null&&u.records)&&(u==null?void 0:u.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:u==null?void 0:u.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>p({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>p({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>i({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const ys=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),Yr=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Xr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ys,{language:"javascript",value:t,onChange:o})})]}),Zr=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function eo(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(""),m=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:g}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:v}=s.useEditorActions(),j=E=>{var S,N;return JSON.stringify({...E,data:{...E.data,datasets:(N=(S=E.data)==null?void 0:S.datasets)==null?void 0:N.map(D=>({...D,data:[]}))}},null,2)},b=()=>{var S,N;if(!((S=p==null?void 0:p.records)!=null&&S.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:g});if(E){r(j(E)),i(((N=m.preferences)==null?void 0:N.customVisualCode)||"");const D=s.merge(E,h);l(j(D))}},C=()=>{try{if(c&&v(c),o){const E=JSON.parse(o),S=s.getObjectDiff(JSON.parse(n),E);x(S),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Yr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Xr,{customCode:c,cardCustomCfgString:f,mergedConfig:o,onConfigChange:E=>l(E??""),onCodeChange:E=>i(E??"")})]}),e.jsx(Zr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{l(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function us(t){const[a,n]=M.useState(null);return a}function $s(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function so({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:l,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=$s();function d(u,m){r(null),o({}),l(u),m&&c({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var m;if(i){const f=(await Promise.all((m=i==null?void 0:i.plugins)==null?void 0:m.map(async p=>(await s.loadManifest(p.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:p.value}))))).flat();n(f)}})()},[i]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((u,m)=>e.jsx(to,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},u.url+u.name+m))})]})}const to=({text:t,icon:a,onClick:n})=>{const r=us(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function qs(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function no(t){return Me({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function Gs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Hs(t){return Me({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function Ks(t){return Me({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Qs(t){return Me({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function dn({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:l,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){l(null),r({}),n(m),["custom","text","map"].includes(m)&&(o(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(Ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(As,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(Gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(Ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(Rs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(Os,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(Is,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Qs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Ct,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(Ls,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})})]})}function ao({chartType:t,className:a,customIcon:n,componentName:r}){const o=us();switch(t){case"bar":return e.jsx(rs,{className:a});case"line":return e.jsx(os,{className:a});case"pie":return e.jsx(is,{className:a});case"radar":return e.jsx(Rs,{className:a});case"scatter":return e.jsx(As,{className:a});case"bubble":return e.jsx(Gs,{className:a});case"doughnut":return e.jsx(Ms,{className:a});case"stackedBar":return e.jsx(Ts,{className:a});case"stackedLine":return e.jsx(Ks,{className:a});case"polarArea":return e.jsx(qs,{className:a});case"funnel":return e.jsx(Hs,{className:a});case"tornado":case"pyramid":return e.jsx(Os,{className:a});case"range":return e.jsx(Is,{className:a});case"kpi":return e.jsx(Qs,{className:a});case"text":return e.jsx(Ge,{className:a});case"map":return e.jsx(Ls,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx($e,{className:a});default:return e.jsx(ls,{className:a})}}function un({variant:t="ghost"}){var l,c;const[a,n]=M.useState(!1),r=s.useEditorStore(i=>i.card),o=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(ao,{className:"size-4",chartType:o,customIcon:(l=r.customCardPreferences)==null?void 0:l.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(dn,{onChartTypeChange:()=>n(!1)}),e.jsx(so,{onChartTypeChange:()=>n(!1)})]})]})}const Ke="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function ft(t,a){var r,o,l;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((l=(o=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:l.type)||"linear"}function ro(){var T,F,z,_,P,Y;const[t,a]=M.useState(!1),n=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.preferences}),r=s.useEditorStore(W=>{var V;return(V=W.card)==null?void 0:V.type}),o=s.getNumberAxis(n,{}),[l,c]=M.useState(ft(n,r)),[i,d]=M.useState(((z=(F=(T=n==null?void 0:n.chartOptions)==null?void 0:T.scales)==null?void 0:F[o])==null?void 0:z.min)||""),[u,m]=M.useState(((Y=(P=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:P[o])==null?void 0:Y.max)||""),[h,f]=M.useState(i||u?"custom":"auto"),[p,g]=M.useState(""),[x,v]=M.useState(0),[j,b]=M.useState(""),[C,R]=M.useState(""),[E,S]=M.useState(""),N=s.useEditorStore(W=>W.actions.setCardPreferences),{updateCardInFrame:D}=s.useEditorActions(),w=s.useEditorStore(W=>W.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var W,V,$,q,U,H,Q,G,Z,te,ae,se,oe,K;c(ft(n,r)),d((($=(V=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:V[o])==null?void 0:$.min)===0?0:""),m(((H=(U=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:U[o])==null?void 0:H.max)||""),g(((te=(Z=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:Z.ticks)==null?void 0:te.stepSize)||""),v(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.decimalPlaces)||0),b(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),R(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.currency)||""),S(((K=n==null?void 0:n.numberAxisFormat)==null?void 0:K.locale)||"")},[t,n,o,r]);function k(W,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(W)}function O(){const W=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>R(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),W.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:E,onValueChange:V=>S(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>v(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ke}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:l,onValueChange:W=>c(W),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),l=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:h,onValueChange:W=>f(W),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&l=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:W=>d(V=>k(V,W.target.value)),className:`col-span-1 h-8 w-full ${Ke}`}),e.jsx(s.Input,{value:u,onChange:W=>m(V=>k(V,W.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ke}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:p,onChange:W=>g(V=>k(V,W.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ke}`})]})]})}function y(){var q;let W={};h==="custom"&&(W={min:i,max:u,ticks:{stepSize:p}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:l,...l==="linear"?W:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:E}};console.log(V),N(V);const $={...w,preferences:V};D($)}return e.jsxs(s.Popover,{onOpenChange:W=>a(W),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(Zn,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[O(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function oo(){const t=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.position}),a=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.align}),n=s.useEditorStore(i=>{var d,u,m,h;return(h=(m=(u=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:u.plugins)==null?void 0:m.legend)==null?void 0:h.display}),{setLegendOptions:r}=s.useEditorActions(),o=i=>{r({display:i,position:t,align:a})},l=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(da,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>l("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>l("left"),children:e.jsx(_n,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>l("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>l("right"),children:e.jsx(Vn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(On,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Rn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Bn,{className:"size-4"})})]})]})]})]})]})})]})}function io(){const t=s.useEditorStore(l=>{var c,i;return(i=(c=l.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(l=>l.card.type),{setChartOrientation:n}=s.useEditorStore(l=>l.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(lt,{className:"size-4"}):e.jsx(it,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function mn(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:o}=s.useEditorActions();function l(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(io,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ro,{}),e.jsx(oo,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(r==="xy"||!r)&&e.jsx(ia,{className:"size-4"}),r==="x"&&e.jsx(Jn,{className:"size-4"}),r==="y"&&e.jsx(ba,{className:"size-4"}),r==="none"&&e.jsx(ka,{className:"size-4"})]})]}):null}function lo(){const t=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:l}=s.useEditorActions(),c=(g,x)=>{g.dataTransfer.setData("tabIndex",x.toString())},i=g=>{g.preventDefault()},d=(g,x)=>{const v=g.dataTransfer.getData("tabIndex");if(v===x.toString())return;const j=Array.from(t.cards),[b]=j.splice(parseInt(v),1);j.splice(x,0,b),n({...t,cards:j})};function u(g){const x=t.cards.filter(b=>b.id!==g),v=x[0],j={...t,cards:x,activeCardId:v.id};n(j),r(v.id),o(v)}function m(g,x){const v={...t,cards:[...t.cards,x],activeCardId:g.id};n(v),r(x.id)}function h(){const g={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,g)}function f(g){const x={dataSource:g.dataSource,connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(g,x)}function p(g,x){return g.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||g.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:v}),l({...x,displayTab:v})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ea,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((g,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,x),onDragOver:i,onDrop:v=>d(v,x),className:"",value:g.id,children:[p(t,g),e.jsx(s.Editable,{enabled:t.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),l({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),t.activeCardId===g.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(g.id)})]},g.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(Xn,{className:"h-4 w-4"})})]})})}function hn(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:l,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(a);function f(x){const v=t.cards.find(j=>j.id===x);if(v!=null&&v.sql){r||i(!0),l(x);return}if(v!=null&&v.queryConfig){r&&i(!1),p(x),l(x);return}r||p(x),l(x)}function p(x){const v={...t,cards:t.cards.map(b=>b.id===a.id?a:b),activeCardId:x};o(v);const j=v.cards.find(b=>b.id===x);j.sql&&d(!0),c(j)}function g(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(cn,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:g()},x.id)),e.jsx(lo,{})]})}function Qe({children:t}){s.useEditorStore(b=>b.frame);const a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.isShowingVisual),o=s.useDashboardStore(b=>b.isVisualEditing),l=s.useEditorStore(b=>b.pythonStdOut);s.useEditorStore(b=>b.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m}=s.useEditorActions(),{data:h,isLoading:f,isFetching:p,errorMessage:g}=s.useDashboardCardQuery(a);function x(){const b=JSON.stringify(h==null?void 0:h.records,null,2),C=new Blob([b],{type:"application/json"}),R=URL.createObjectURL(C),E=document.createElement("a");E.href=R,E.download=`${a.title}.json`,E.click()}function v(){const C=[Object.keys(h==null?void 0:h.records.reduce((N,D)=>({...N,...D}),{})).join(","),...((h==null?void 0:h.records)||[]).map(N=>Object.values(N).join(","))].join(`
419
+ `),R=new Blob([C],{type:"text/csv"}),E=URL.createObjectURL(R),S=document.createElement("a");S.href=E,S.download=`${a.title}.csv`,S.click()}function j(){const b=`Can you get the documentation for ${a.type} chart?`;u(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(f||p)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(un,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(Gn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(eo,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(no,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:x,children:e.jsx(ta,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(mn,{})]}),n&&e.jsx(uo,{})]}),r?e.jsx(hn,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:l&&e.jsx(co,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(Wr,{data:(h==null?void 0:h.records)||[]}),g&&e.jsx(tn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function co(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function uo(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function mo(){var x,v;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=$s(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function m(j,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function h(j){var C,R;const b=(C=o==null?void 0:o.cards)==null?void 0:C.filter(E=>{var S;return((S=E==null?void 0:E.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(R=j==null?void 0:j.dataInputs)==null?void 0:R.map((E,S)=>{var N,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((D=(N=t==null?void 0:t.dataInputCardIds)==null?void 0:N[S])==null?void 0:D.cardId)||"",onValueChange:w=>m(S,w)})]},S+Math.random())})})}function f(j,b,C=[],R=""){var E,S;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[b])||R,onChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N.target.value}})}},b):j==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:C,value:((S=t==null?void 0:t.settings)==null?void 0:S[b])||R,onValueChange:N=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:N}})}}):null:null}function p(j){const b=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([C,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,C,R.options,R.defaultValue)]},C))})}function g(j){t&&c({...t,visualType:j,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(qn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:g,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(he,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(j=>j.type===l).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Le(){const[t,a]=M.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),M.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function c(u,m){var h,f;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):o({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(p=>p.columnIndex!==u)}),a(p=>{const g=[...p];return g[u]=!1,g}))}function i(u,m){var f;const h=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);o({...n,onClickFilter:h})}function d(u){var m,h,f,p;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(g=>g.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(p=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===u))==null?void 0:p.expression,onChange:g=>i(u,g),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),l==null?void 0:l.map((u,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const g=[...p];return g[m]=!p[m],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})]})}function ho({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,l=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...l};h.datalabels=m;const f=n==null?void 0:n.map(p=>p.idx===u?h:p);r({...a,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Mt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ua,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ha,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ma,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function xo(){const t=s.useEditorStore(l=>l.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ws({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function xn(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=xo();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:pn(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(fn,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function pn(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function fn({col:t,idx:a,className:n,iconClassName:r,children:o}){const l=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...l,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const f=c==null?void 0:c.map(p=>p.idx===a?h:p);d({...l,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ws,{className:"max-w-[100px]",title:t,children:pn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(rs,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(os,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(wt,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ho,{idx:a})]})]})}function gn(){const t=s.useEditorStore(p=>p.selectedConnectionId),a=s.useEditorStore(p=>p.selectedDatamodelId),n=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedTableName),l=s.useDashboardStore(p=>p.dashboard.filters)||[],c=s.useDashboardStore(p=>p.actions.addFilter),i=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function f(p,g="dashboard"){var N;const x=s.fmt(p.column_name),v=s.fmt(n||""),j=s.fmt(r||""),b=s.fmt(m);let C=s.getQualifiedTableName({schemaName:j,tableName:b,connectionType:h,databaseName:v}),R=`${C}.${x}`;const E=(N=u==null?void 0:u.find(D=>D.id===a))==null?void 0:N.name;a&&a!=="none"&&(R=`${s.DATAMODEL_NAMESPCACE}.${E}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${E}`);const S=l==null?void 0:l.find(D=>D.column===R&&D.table===b&&(D.database===v||D.database===n));if(S)d(S.id),i(S.id);else{const D=s.v4();return m==="api"&&t?(c({location:g,id:D,column:R,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),D):(c({id:D,location:g,column:R,title:p.column_name,dataType:p.data_type,table:o||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,C,x)}),D)}}return{assignFilter:f}}function _e(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();function l(i){const d=o(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(po,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function po({columns:t,onSelect:a}){var c;const[n,r]=ue.useState(!1),[o,l]=ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===o?"":d;l(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function fo({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(xn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function ms(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?l():c()})}function go({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(ms,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}const jo={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},yo={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function vo(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:bo(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ms,{}),e.jsx(Le,{}),e.jsx(_e,{})]})]})}function bo(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(jo,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(yo,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function No(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function vs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Co=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],So=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],wo=So.map(t=>({label:t,value:t}));function ko(){var d,u,m,h,f,p,g,x,v,j,b,C,R,E,S,N,D,w;const t=s.useEditorStore(L=>L.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=M.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(L=>({label:L,value:L}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(vs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(vs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),o({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),o({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:c,value:((p=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:Co,value:((x=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:wo,value:((j=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(vs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var k;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(E=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:S[0])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(D=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var k,O,A,I;o({...t.preferences,mapVisualOptions:{...(k=t.preferences)==null?void 0:k.mapVisualOptions,projectionOffset:[((I=(A=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Do(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=s.useEditorStore(o=>o.actions);function n(o){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function We({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[t!=="text"&&e.jsx(ms,{}),t==="text"&&e.jsx(Do,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function Eo(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(xn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})]})})}function To({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),n=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(_e,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const Io=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ao=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Mo=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Lo(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Eo,{});case"tornado":case"pyramid":return e.jsx(We,{docContent:Io,cardType:n});case"kpi":return e.jsx(No,{});case"line":case"bar":return e.jsx(fo,{cardType:n});case"range":return e.jsx(We,{docContent:Ao,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(We,{cardType:n});case"bubble":case"scatter":return e.jsx(go,{cardType:n});case"table":return e.jsx(To,{cardType:n});case"text":return e.jsx(We,{docContent:Mo,cardType:n,suffix:"Visual"});case"map":return e.jsx(ko,{});case"custom":return e.jsx(mo,{});default:return e.jsx(vo,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function jn({label:t,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function l(c){r(c)}return e.jsx(he,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Ro=[{label:"Sum",value:"SUM",logo:e.jsx(At,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ue,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Pn,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Oo({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Ro;s.isTextDataType(t.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};a(t.id,l)}return e.jsx(jn,{column:t,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Bo=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Fo({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const o={...t,granularity:r,label:Pe(t.name,r)};a(t.id,o)}return e.jsx(jn,{column:t,functions:Bo,onFunctionChange:r=>n(r),label:"Granularity"})}function zo({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),o=M.useMemo(()=>{let i=[];(n===Ee||n===Te||n===Ie)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&a(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function yn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(fn,{idx:l,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(ms,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Po({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[o,l]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id,data:{type:a}}),x=f?{opacity:g?.5:void 0,transform:s.CSS.Translate.toString(f),transition:p}:void 0,v=s.isTextDataType(t.type);function j(S){const N=s.isNumberDataType(S.data_type),D=s.isTextDataType(S.data_type),w=s.isDateDataType(S.data_type),L=N?"number":D?"string":w?"date":"string";if(r===Ee){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};c(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,role:"groupby",label:Pe(S.column_name,"month"),granularity:"month"};c(t.id,k)}}if(r===Ie){if(D){const k={id:t.id,name:S.column_name,type:L,role:"groupby"};d(t.id,k)}if(w){const k={id:t.id,name:S.column_name,type:L,label:Pe(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,k)}}if(r===Te){const k={id:t.id,name:S.column_name,type:L,role:"metric",label:He(S.column_name,"SUM"),aggregate:N?"SUM":"COUNT"};i(t.id,k)}}function b(){if(r===Te)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(yn,{column:t})})}function C(){const S=s.isDateDataType(t.type);if(r===Te)return e.jsx(Oo,{column:t});if((r===Ee||r===Ie)&&S)return e.jsx(Fo,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ee||r===Ie)&&v}),children:e.jsx(zo,{col:t,onChange:j,droppableId:r})})}function E(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>l(!o),children:o?e.jsx(Sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Dt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[E(),C(),R()]}),o&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function bs({id:t,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:l}){var x,v;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(j=>j.activeId),m=s.useEditorStore(j=>{var b;return(b=j.card)==null?void 0:b.type}),h=i||((v=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:v.type)===o,f=u?r:n,p=o===ss?"Rows":o===ts?"Pivot Columns":"Columns";function g(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:p})]}),g(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(j=>j.id===en.id?e.jsx(_o,{},j.id):e.jsx(Po,{droppableId:t,type:o,column:j,onRemoveColumn:l},j.id))})]})})}function _o(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function vn({children:t,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function Vo(){const t=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.orderBy})||[],a=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.groupByColumns})||[],n=s.useEditorStore(j=>{var b;return(b=j.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx($n,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(zn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(j=>!t.some(b=>b.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function f(j,b){const C=p(j);return C?C.role==="metric"?b==="asc"?u:m:b==="asc"?i:d:null}function p(j){return c.find(b=>b.id===j)}function g(j){const b=t.find(C=>C.columnId===j);if(b){const C={...b,direction:b.direction==="asc"?"desc":"asc"};l(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function v(j){const b=t.find(C=>C.columnId===j);b&&o(b)}return e.jsx(s.SortableContext,{items:t.map(j=>Ve(j.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var b,C;return e.jsx(vn,{id:Ve(j.columnId),type:_s,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Dt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ws,{className:"w-[175px] text-sm",children:((b=p(j.columnId))==null?void 0:b.label)||((C=p(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>g(j.columnId),className:"rounded-sm p-0",children:f(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(j.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},j.columnId)},Ve(j.columnId))})]})})}function Uo(){const t=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(v=>v.card.type),n=s.useDndStore(v=>v.previewGroupByColumns),r=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.metricColumns)||[]}),o=s.useDndStore(v=>v.previewMetricColumns),l=s.useEditorStore(v=>{var j;return((j=v.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(v){i(v)}function h(v){d(v)}function f(v){u(v)}let p="Group By",g="Metrics",x="Stack By";return a==="table"&&(p="Rows",g="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(dn,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(bs,{onRemoveColumn:m,sortableType:ss,id:Ee,label:p,columns:t,previewColumns:n}),e.jsx(bs,{onRemoveColumn:f,sortableType:ts,id:Ie,label:x,columns:l,previewColumns:c}),e.jsx(bs,{onRemoveColumn:h,sortableType:Ss,id:Te,label:g,columns:r,previewColumns:o}),e.jsx(Vo,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Js({children:t,column:a,id:n,sortableType:r,className:o}){const[l,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var f,p;return(p=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:p.some(g=>g.filterColumnName===a.name)});function m(h){i(h)}return e.jsx(vn,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!l&&"rounded-b-md",l&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function $o({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var R,E;return(E=(R=C.card)==null?void 0:R.queryConfig)==null?void 0:E.filters}),o=s.useEditorStore(C=>{var R,E;return(E=(R=C.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:E.find(S=>S.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),u=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:f,isLoading:p,isFetching:g,isError:x}=s.useFilterQuery(h),v=M.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(E=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return E[S]===void 0&&(S=S.toLowerCase()),{id:E[S],value:E[S]}}):[]},[f,h.column]);function j(C){const R=C.map(E=>E.id);m(t.name,R)}function b(){return p||g?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(qo,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:j,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Js,{className:"w-60",id:t.id,sortableType:a,column:t,children:b()})}function qo({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Go({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:p,setDateRange:g,initialDateRange:x}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:v}=s.useEditorActions();function j(R){var S,N;const E={gte:(S=R==null?void 0:R.from)==null?void 0:S.toISOString(),lte:(N=R==null?void 0:R.to)==null?void 0:N.toISOString()};v(t.name,E)}function b(){v(t.name,null,!0),g(x)}function C(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:p,setDateRange:g,onApply:j,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Js,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Ho({id:t,label:a,columns:n,previewColumns:r,sortableType:o}){var g,x;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(v=>v.activeId),u={},m=c||((x=(g=i==null?void 0:i.data)==null?void 0:g.current)==null?void 0:x.type)===o;function h(){if(!p||p.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(v){const j=s.isDateDataType(v.type);return v.id===en.id?e.jsx(Js,{id:v.id,sortableType:o,column:v,children:e.jsx(Ko,{})},v.id):j?e.jsx(Go,{droppableId:t,sortableType:o,column:v},v.id):e.jsx($o,{droppableId:t,sortableType:o,column:v},v.id)}const p=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:p==null?void 0:p.map(v=>f(v))})]})})}function Ko(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Qo(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),a=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Ho,{onRemoveColumn:r,sortableType:ks,id:ws,label:"Filters",columns:t,previewColumns:a})})}function Wo(){const t=s.useEditorStore(l=>l.card),a=s.useEditorStore(l=>l.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ds,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(an,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Us,{}),e.jsx(Vs,{variant:"default"})]})]})}function Jo(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=a.current)==null||m.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Lo,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Qe,{})})]}):e.jsx(Qe,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Uo,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(Wo,{}),e.jsx(Qo,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Qe,{})})]})})]}):e.jsx(Qe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?l():c()})}function Yo(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[o,l]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.sql}),d=s.useEditorStore(B=>B.isDevMode),u=s.useEditorStore(B=>{var J;return(J=B==null?void 0:B.card)==null?void 0:J.python}),{setCardPython:m,setCardSql:h,setRunSql:f,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],v=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),b=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),R=s.useEditorStore(B=>B.selectedTableName),E=s.useEditorStore(B=>B.selectedConnectionId),S=s.useEditorStore(B=>B.selectedSchemaName),N=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:D,refetch:w,data:L}=s.useDashboardCardQuery(b),{setTriggerAIRun:k,setCurrentAssitantScope:O,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:T}=s.useEditorAside(),{messages:F,setMessages:z,reload:_,error:P,append:Y,input:W,setInput:V,status:$,handleInputChange:q,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:Q,onFinish(B,J){G(J.usage),r(""),J.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&v&&(Y({role:"user",content:v}),k(!1))},[j,v,Y,k]);async function Q({toolCall:B}){var J,ie,ye,ke;if(["createChartFromSql","createForecast"].includes(B.toolName)){const ne=B.args.sql,le=B.args.python,ce=B.args.chartType;return p(ce),h(ne),m(le),f(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:u||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),se(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const ne=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,p(ne),A(le),h(void 0),m(void 0);const ce=await w();return(J=ce==null?void 0:ce.data)!=null&&J.error?{status:"error",queryConfig:le,message:(ie=ce==null?void 0:ce.data)==null?void 0:ie.error.message}:(ye=ce==null?void 0:ce.data)!=null&&ye.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(ke=ce==null?void 0:ce.data)==null?void 0:ke.records}}else r("Analyzing...")}}function G(B){l(J=>J?{promptTokens:J.promptTokens+B.promptTokens,completionTokens:J.completionTokens+B.completionTokens,totalTokens:J.totalTokens+B.totalTokens}:B)}function Z(B){const J=s.removeFromScopeArray(x,B);te(J)}function te(B){const J=s.sanitizeAIScope(B);O(J),z(ie=>[...ie,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}])}function ae(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelId:T||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||""},J=s.dedup([...x,B]);te(J)}function se(){const B={databaseName:C||"",schemaName:S||"",tableName:R||"",datamodelName:s.resolveDatamodelName(I),connectionId:E||"",connectionType:y||"",datamodelId:T||""};if(!s.isInAiScopeArray([...N||[],...x],B)||x.length===0){const ie=s.dedup([...N||[],...x,B]).filter(ye=>ye.connectionId===B.connectionId);te(ie)}}const oe=!["ready","error"].includes($),K=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:_,append:Y,input:W,setInput:V,isLoading:oe,handleSetAIScope:se,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:O,handleInputChange:q,handleSubmit:U,stop:H,chatStatus:$,toolStatus:n,llmUsage:o,onFinish:t,errorMessage:K}}const Xo=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function gt(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[o,l]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,u]=M.useState(!1),m=s.useCurrentAIContext(),{setCurrentAIContext:h}=s.useAIActions(),f=s.useDashboardStore(H=>H.dashboard.aiContext),p=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),v=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:b,setCardPython:C}=s.useEditorActions(),{setDataSource:R}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:S,setMessages:N,reload:D,append:w,input:L,setInput:k,isLoading:O,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:T,llmUsage:F,errorMessage:z}=Yo();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:S}),M.useEffect(()=>{var H;v&&((H=a.current)==null||H.focus(),h({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[v,p,h]);function _(H,Q){Q==="sql"?(g(H),x(!0)):Q==="python"&&(C(H),x(!0))}function P(){var H;(H=f==null?void 0:f.selectedEntities)==null||H[0],u(!0)}function Y(){m.selectedEntities.length===0&&h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]})}function W(H){Y();const Q={role:"user",content:H.title+" "+H.subtitle};w(Q)}function V(H){Y(),w({role:"user",content:H})}function $(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(S==null?void 0:S.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[$(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),D()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{b(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:S,showTools:o,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:S,chatStatus:T,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!E&&e.jsx(s.Placeholders,{onClick:W,placeholders:Xo}),e.jsx("div",{children:U&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:k,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Y(),I(H)},isLoading:O,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:d,onOpenChange:u,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function bn(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(o=>{const l=s.getQualifiedEntityName(o.source),c=s.getQualifiedEntityName(o.target);return l===t&&c===a||l===a&&c===t})}function Zo(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!bn(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function Ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function Es(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const Ys=t=>{var k;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,f=M.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),p=M.useCallback((O,A)=>{if(h)switch(O){case"groupBy":{a(h,{groupByColumns:A});break}case"metrics":{a(h,{metricColumns:A});break}case"pivotBy":{a(h,{pivotByColumns:A});break}case"sortBy":{a(h,{sortByColumns:A});break}}},[h,a]),g=M.useCallback((O,A,I)=>{if(!h)return;const T=f(O)[A];if(T)switch(O){case"groupBy":n(h,T.id,{label:I});break;case"metrics":r(h,T.id,{label:I});break;case"pivotBy":o(h,T.id,{label:I});break;case"sortBy":l(h,T.id,{label:I});break}},[h,f,n,r,o,l]),x=M.useCallback((O,A)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aggregate:A,label:s.getAggregationLabel(y.name,A)})},[h,f,r]),v=M.useCallback((O,A,I)=>{if(!h)return;const T=f("groupBy")[O];if(!T)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(h,T.id,F)},[h,f,n]),j=M.useCallback((O,A)=>{if(!h)return;const y=f("groupBy")[O];y&&n(h,y.id,{granularity:A})},[h,f,n]),b=M.useCallback((O,A)=>{if(!h)return;const y=f("metrics")[O];y&&r(h,y.id,{aliasTemplate:A})},[h,f,r]),C=M.useCallback((O,A)=>{if(console.log("handleValueAliasesChange",O,A),!h)return;console.log("handleValueAliasesChange",O,A);const y=f("metrics")[O];y&&(console.log("handleValueAliasesChange",A),r(h,y.id,{valueAliases:A}))},[h,f,r]),R=M.useCallback(O=>{h&&a(h,{comparisonType:O})},[h,a]),E=M.useCallback(O=>{h&&a(h,{showTrendline:O})},[h,a]),S=M.useCallback(O=>{h&&a(h,{trendlineWindow:O})},[h,a]),N=M.useCallback(O=>{h&&a(h,{trendlineGranularity:O})},[h,a]),D=M.useCallback(O=>{h&&a(h,{targetValue:O})},[h,a]),w=M.useCallback(O=>{var _;if(!h)return;const A=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=Zo(O,A,I);if(!y.isValid){y.showError&&Ds();return}const T=s.getSmartContainerForField(O),F=f(T);if(Es(O,F))return;const z=s.getNewField(O,T);z&&p(T,[...F,z])},[h,(k=t==null?void 0:t.config)==null?void 0:k.joinPlan,f,p]),L=M.useCallback((O,A)=>{if(!h)return;const y=f(O)[A];if(y){if(O!=="sortBy"){const T=f("sortBy"),F=T.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==T.length&&a(h,{sortByColumns:F})}switch(O){case"groupBy":c(h,y.id);break;case"metrics":i(h,y.id);break;case"pivotBy":d(h,y.id);break;case"sortBy":u(h,y.id);break}}},[h,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:p,updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:D,cardType:m}};function ei({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function si({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),u=s.useEditorStore(g=>g.card),{handleFieldClick:m}=Ys(u),h={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const f=g=>{const x=(g||"").toLowerCase();switch(s.getDataType(x)){case"number":return Ue;case"date":return s.Calendar;case"boolean":return Ze;case"json":return rt;case"geo":return ot;default:return Ge}},p=g=>{const x=(g||"").toLowerCase(),v=s.getDataType(x);return v==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):v==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):v==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):v==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):v==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(rt,{className:"h-3 w-3"})}):v==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ot,{className:"h-3 w-3"})}):v==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(St,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[p(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(ei,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function ti(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),o=s.useEditorStore(C=>C.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const R=s.getDataType(C.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(C=>m(C)===n)).reduce((C,R)=>{const E=R.qualifiedEntityName||"Other Fields";return C[E]||(C[E]={label:s.toLabel(R.entityName),fields:[]}),C[E].fields.push(R),C},{}),g=Object.keys(f),x=u.filter(C=>m(C)==="dimensions").length,v=u.filter(C=>m(C)==="metrics").length,j=u.filter(C=>m(C)==="calculated").length,b=u.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[l.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(St,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:g,className:"space-y-2",children:Object.entries(f).map(([C,R])=>{const E=c.find(S=>S.entityName===C)||{entityName:C,label:R.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:E.label||E.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(S=>e.jsx(si,{field:S},S.id))})})]},C)})}),Object.keys(f).length===0&&l.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&l.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function ni(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ti,{})," "]})}function ai({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[o,l]=M.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,N={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,N]}),l(new Set([...o,N.id]))},i=S=>{r({...n,joins:n.joins.filter(N=>N.id!==S)}),l(new Set([...o].filter(N=>N!==S)))},d=(S,N)=>{var k,O;const D=n.joins.find(A=>A.id===S);if(!D)return;const w={...D,...N},L=n.joins.map(A=>A.id===S?w:A);if((k=w.source)!=null&&k.name&&((O=w.target)!=null&&O.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},T=[...w.joinKeyGroups];T[0]={...T[0],keys:[y]},w.joinKeyGroups=T,L[L.findIndex(F=>F.id===S)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N>0){const D=[...n.joins],w={...D[N]},L={...D[N-1]};D[N]=L,D[N-1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},moveJoinDown:S=>{const N=n.joins.findIndex(D=>D.id===S);if(N<n.joins.length-1){const D=[...n.joins],w={...D[N]},L={...D[N+1]};D[N]=L,D[N+1]=w,D.forEach((O,A)=>{O.sequence=A+1});const k={...n,joins:D};r(k)}},toggleJoinExpansion:S=>{const N=new Set(o);N.has(S)?N.delete(S):N.add(S),l(N)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const N=n.joins.findIndex(w=>w.id===S);if(N===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,N).forEach(w=>{D.add(w.source.name),D.add(w.target.name)}),a.filter(w=>D.has(w.name))},getAvailableTargetEntities:S=>a.filter(N=>N.name!==S),addJoinKeyGroup:S=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const D=[...N.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:D})},updateGroupOperator:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N]={...L[N],operator:D},d(S,{joinKeyGroups:L})},removeJoinKeyGroup:(S,N)=>{const D=n.joins.find(L=>L.id===S);if(!D)return;const w=[...D.joinKeyGroups];w.splice(N,1),d(S,{joinKeyGroups:w})},addJoinKey:(S,N)=>{const D=n.joins.find(A=>A.id===S);if(!D)return;const w=a.find(A=>A.name===D.source.name),L=a.find(A=>A.name===D.target.name),k=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};k[N]={...k[N],keys:[...k[N].keys,O]},d(S,{joinKeyGroups:k})},updateJoinKey:(S,N,D,w,L)=>{const k=n.joins.find(T=>T.id===S);if(!k)return;const O=a.find(T=>T.name===k.source.name),A=a.find(T=>T.name===k.target.name),I=[...k.joinKeyGroups],y=I[N].keys[D];w==="sourceColumnName"&&O?I[N].keys[D]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[N].keys[D]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[N].keys[D]={...y,operator:L}),d(S,{joinKeyGroups:I})},removeJoinKey:(S,N,D)=>{const w=n.joins.find(k=>k.id===S);if(!w)return;const L=[...w.joinKeyGroups];L[N].keys.splice(D,1),d(S,{joinKeyGroups:L})},generateSQLPreview:()=>{const S=[...n.joins].sort((w,L)=>w.sequence-L.sequence),N=n.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
420
+ FROM ${N.name}`;return S.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const k=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var T,F,z,_;return((T=y.source)==null?void 0:T.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),O=k.length>1?k.join(" OR "):k[0]||"condition_here";D+=`
421
421
  ${w.joinType} JOIN ${L.name}
422
- ON ${O}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(k=>!k.source.name||!k.target.name||!k.operator))))}}function ri({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:h,removeJoin:m,updateJoin:f,moveJoinUp:x,moveJoinDown:g,toggleJoinExpansion:p,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:E,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:D,isValidConfiguration:w}=ai({initialJoinPlan:t,availableDataSources:a}),L=k=>{const O=c.find(A=>A.entityName===k);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:k=>{const O=a.find(A=>A.name===k);u({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:k,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(k=>{const O=a.find(y=>y.name===k.source.name),A=a.find(y=>y.name===k.target.name),I=d.has(k.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,O&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),disabled:k.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(k.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:k.source.name,onValueChange:y=>{const T=a.find(F=>F.name===y);f(k.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(k.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:y=>f(k.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:k.target.name,onValueChange:y=>{const T=a.find(F=>F.name===y);f(k.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?j(k.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),k.source.name&&k.target.name&&O&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((y,T)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",T+1]}),T>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>C(k.id,T,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(k.id,T),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:V=>S(k.id,T,z,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(k.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:F.operator,onValueChange:V=>S(k.id,T,z,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:V=>S(k.id,T,z,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(k.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(k.id,T,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(k.id,T),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function jt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(ri,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function oi({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,i)=>c.sequence-i.sequence),l=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=n.find(d=>d.name===o.source.name),i=n.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ii(){var h,m;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=M.useState(!1),l=((m=t==null?void 0:t.dataSource)==null?void 0:m.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),o(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const f=[...n.joins].sort((p,v)=>p.sequence-v.sequence),x=n.baseEntity;if(!x.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
423
- FROM ${x.name}`;return f.forEach(p=>{const v=l.find(C=>C.name===p.target.name);if(!v)return;const j=p.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(E=>{var S,N,D,w;return((S=E.source)==null?void 0:S.name)&&((N=E.target)==null?void 0:N.name)&&((D=E.source)==null?void 0:D.entityName)&&((w=E.target)==null?void 0:w.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
424
- ${p.joinType} JOIN ${v.name}
425
- ON ${b}`}),g};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(oi,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function li({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function ci({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function di({isVisible:t,onToggleVisibility:a}){const n=s.useEditorStore(x=>x.isDevMode),r=s.useEditorStore(x=>x.card.connectionId),o=s.useDashboardStore(x=>x.isVisualEditing),[l,c]=M.useState(!1),[i,d]=M.useState(!0),u=s.useEditorStore(x=>x.card.dataSource),{updateDataSource:h}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},f={...m,...u,selectedEntities:(u==null?void 0:u.selectedEntities)||[]};return M.useEffect(()=>{o&&(n||(!r||!u)&&c(!0))},[u,r,n,o]),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":!i}),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:()=>d(!i),className:"h-6 w-6 p-0",children:i?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:()=>c(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${i?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[f.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[f.selectedEntities.slice(0,3).map((x,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(x),e.jsx("button",{onClick:p=>{p.stopPropagation();const v=f.selectedEntities.filter(j=>!(j.name===x.name&&j.type===x.type));h({...m,...u,selectedEntities:v})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(li,{entity:x})]},`${x.type}-${x.name}-${g}`)),f.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:["+",f.selectedEntities.length-3," more"]})}),e.jsx(ci,{entities:f.selectedEntities.slice(3)})]})]})}),e.jsx(ii,{})]})]}),e.jsx(ni,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],dialogMode:"dataSource",open:l,onOpenChange:c,dataSource:f,fallbackDataSource:m})]})}const Xe=[{id:"table",icon:ls,label:"Table"},{id:"bar",icon:rs,label:"Bar Chart"},{id:"line",icon:os,label:"Line Chart"},{id:"area",icon:wt,label:"Area Chart"},{id:"stackedBar",icon:Ts,label:"Stacked Bar Chart"},{id:"combo",icon:Qn,label:"Combo Chart"},{id:"stackedLine",icon:Ks,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:is,label:"Pie Chart"},{id:"doughnut",icon:Ms,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Rs,label:"Radar Chart"},{id:"polarArea",icon:qs,label:"Polar Area Chart"},{id:"tornado",icon:Os,label:"Tornado Chart"},{id:"range",icon:Is,label:"Range Chart"},{id:"kpi",icon:Qs,label:"KPI"},{id:"text",icon:Ct,label:"Text"},{id:"map",icon:Ls,label:"Map"}],Xs=t=>{const a=t.toLowerCase();for(const n of Xe)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},ui="chart-selector-standard-first";function mi(){const[t,a]=s.useLocalStorageState(ui,!0);return{standardFirst:t,updatePreference:a}}const yt=({pluginVisual:t,index:a,onSelect:n})=>{const r=us(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Xs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},vt=["default","standardPlugin","customPlugin"];function hi({selectedChart:t,onChartChange:a}){var S;const[n,r]=M.useState([]),[o,l]=M.useState(!1),{data:c}=$s();mi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";Fs(d);const{setCardType:u,setCardPreferences:h,setIsDevMode:m}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:x,setQueryConfig:g}=s.useEditorActions(),[p,v]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>p?[p,...vt.filter(N=>N!==p)]:vt,[p]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(k){return console.error(`Failed to load manifest for plugin ${L.label}`,k),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),h({}),u(N),["custom","text","map"].includes(N)&&(m(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),h({}),u("custom"),x({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var D;if(t==="custom"){const w=s.useEditorStore.getState().card;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=Xe.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var D,w;if(t==="custom"){const L=s.useEditorStore.getState().card,k=(D=L==null?void 0:L.customCardPreferences)==null?void 0:D.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(k&&O)return e.jsx(xi,{icon:k,componentName:O});if(O){const A=Xs(O);if(A)return A}return e.jsx($e,{className:"h-4 w-4"})}const N=Xe.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx($e,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="default",onCheckedChange:D=>v(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Xe.map(D=>{const w=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>b(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=n.filter(w=>w.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=n.filter(w=>w.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const xi=({icon:t,componentName:a})=>{const n=us(),r=Xs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx($e,{className:"h-4 w-4"})},Nn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ge,{className:"h-3 w-3"})})};function pi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[o,l]=M.useState(!1),c=(d=s.useEditorStore(u=>{var h;return(h=u.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function fi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[o,l]=M.useState(""),[c,i]=M.useState(""),d=()=>{a({...t,"":""})},u=m=>{const f={...t};delete f[m],a(f)},h=m=>{const f={...t};delete f[m],f[o]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([m,f],x)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?h(m):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(m),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),l(m),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),l(m),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+x)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function bt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:m=>{c(m.target.value),d(!0)},onFocus:()=>d(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&i&&l!==t?u():m.key==="Escape"&&h()},"aria-label":n||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function gi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var et;const{attributes:i,listeners:d,setNodeRef:u,transform:h,transition:m,isDragging:f}=s.useSortable({id:t.id}),x=s.useEditorStore(X=>X.card),{updateLabel:g,handleAggregationChange:p,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:w}=Ys(x),[L,k]=M.useState(!1),[O,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[T,F]=M.useState(!!t.customFormat),[z,V]=M.useState(t.granularity||"day"),[P,Y]=M.useState(t.aliasTemplate||""),[W,_]=M.useState(t.valueAliases||{}),$=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&v(n,X,""))},q=X=>{y(X),a==="groupBy"&&v(n,"custom",X)},U=X=>{V(X),a==="groupBy"&&j(n,X)},H=X=>{Y(X),a==="metrics"&&b(n,X)},Q=X=>{_(X),a==="metrics"&&C(n,X)},G=X=>{g(a,n,X)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(h),transition:m},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",K=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],B=!oe&&a!=="pivotBy",J=se&&a==="groupBy",ie=!oe&&se&&a==="groupBy",ye=oe&&se&&a==="groupBy",ke=oe&&a==="metrics"&&((et=x.config)==null?void 0:et.comparisonType)==="target",ne=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce=()=>B?e.jsx(bt,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,wn=()=>J?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,kn=()=>ie?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:T?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:K.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),T&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:X=>{X.stopPropagation(),q(X.target.value)},onClick:X=>X.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})}):null,Dn=()=>{var X,ve,Re,st,tt;return ye?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=x.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ve=x.config)==null?void 0:ve.showTrendline)||!1,onCheckedChange:S})]})}),((Re=x.config)==null?void 0:Re.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((st=x.config)==null?void 0:st.trendlineWindow)||30,onChange:In=>{const An=parseInt(In.target.value)||30;N(An)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((tt=x.config)==null?void 0:tt.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},En=()=>{var X,ve;return ke?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(bt,{value:((X=x.config)==null?void 0:X.targetValue)!==void 0&&((ve=x.config)==null?void 0:ve.targetValue)!==null?String(x.config.targetValue):"",onSave:Re=>{!isNaN(Number(Re))&&Re!==null?w(Number(Re)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},Tn=()=>ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{p(n,X)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(yn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(pi,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(fi,{valueAliases:W,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Nn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),k(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ve=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ve),o(ve)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),ce(),wn(),kn(),Dn(),En(),Tn()]})]})}function ji({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),h=s.useEditorStore(g=>g.card.type),m=a.length>0,f=(g,p)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:p})};if(t==="sortBy"&&o===!1)return null;const x=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),x&&e.jsx(ji,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":m?"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,p)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(gi,{field:g,zone:t,index:p,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:h})})},g.id)})})})})]})}function yi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(m=>m.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function vi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(m=>m.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(m=>m.card),{data:h}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(hi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||h}),children:e.jsx(ds,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(wa,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(yi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function bi({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=(E,S)=>{const N=D=>D.id===E?{...D,conditions:D.conditions.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},f=(E,S)=>{const N=D=>D.id===E?{...D,groups:D.groups.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},x=(E,S,N,D)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(k=>k.id===S?{...k,[N]:D}:k)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(D)};r(D(n))},p=(E,S)=>{const N=D=>D.id===E?{...D,logicalOperator:S}:{...D,groups:D.groups.map(N)};r(N(n))},v=(E,S)=>{const N=D=>D.id===E?{...D,negate:S}:{...D,groups:D.groups.map(N)};r(N(n))},j=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},b=(E,S,N)=>{const D=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=D=>{let w="";typeof D.field=="object"?w=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:w=String(D.field);const L=D.operator;let k=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof k=="string"?k=`'${k}'`:Array.isArray(k)&&(k=`'${k.join(", ")}'`);else if(D.field.dataType==="date")(typeof k=="string"||k instanceof Date)&&(k=`DATE('${k}')`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(k)?O=k.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof k=="string"?O=k.split(",").map(A=>{const I=A.trim();return D.field.dataType==="string"?`'${I}'`:I}):typeof k=="number"&&(O=[String(k)]),k=`(${O.join(", ")})`}switch(L){case"contains":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;case"startsWith":return typeof k=="string"?`${w} LIKE '${k.replace(/'/g,"")}%'`:`${w} LIKE '${String(k)}%'`;case"endsWith":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;default:return`${w} ${L} ${k}`}},N=D=>{const w=D.conditions.map(S),L=D.groups.map(I=>N(I)),k=[...w,...L].filter(Boolean);if(k.length===0)return"";const O=k.join(` ${D.logicalOperator} `),A=k.length>1?`(${O})`:O;return D.negate?`NOT ${A}`:A};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:h,removeCondition:m,removeGroup:f,updateCondition:x,updateConditionFields:g,updateGroupOperator:p,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ni({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Ci=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(na,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Si=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function wi({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return n.forEach(u=>{const h=Si(u);d[h]||(d[h]={}),d[h][u.entityId]||(d[h][u.entityId]=[]),d[h][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ni,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([h,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ci(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((f,x)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+x))]},`${d}-${h}`))},d))})]})})]})}function Zs(t){var g;const a=s.useEditorStore(p=>p.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:h,isPending:m,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(p=>({label:p[t.name]||"BLANK",value:p[t.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:m,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=Zs(t),d=h=>{n(a.filter(m=>m!==h))},u=h=>{a.includes(h)?n(a.filter(m=>m!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const m=i.find(f=>f.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(h)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((h,m)=>e.jsxs(s.CommandItem,{onSelect:()=>u(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+m))})]})]})})]})})}const Cn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Cn(n)}),a};function Di({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=Zs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ei=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ti=["=","!=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Mi=["=","!=",">",">=","<","<=","in","not in"];function Li(t){switch(t){case"string":return Ti;case"number":return Ii;case"boolean":return Ai;case"date":return Mi;default:return Ei}}function Sn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:h,setNodeRef:m,transform:f,transition:x,isDragging:g}=s.useSortable({id:t.id}),{isPending:p,error:v}=Zs(t.field),j={transform:s.CSS.Transform.toString(f),transition:x};return e.jsxs("div",{ref:m,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(wi,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Li(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Di,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Ri({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:h,onAddCondition:m,onAddGroup:f,availableFields:x,renderFilterGroup:g,updateConditionFields:p}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id){const O=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&u(t.id,O,A)}},D=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&h(n,O,A)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Sn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:x,updateConditionFields:p},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Oi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:h,removeGroup:m,updateCondition:f,updateConditionFields:x,updateGroupOperator:g,updateGroupNegate:p,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=bi({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=M.useState(!1),D=(k,O,A)=>{const I=y=>y.id===k?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:A,dataType:A.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(k,O=0,A)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.conditions.findIndex(V=>V.id===y.id),z=k.conditions.findIndex(V=>V.id===T.id);F!==-1&&z!==-1&&v(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.conditions.map((I,y)=>e.jsx(Sn,{condition:I,index:y,groupId:k.id,groupLogicalOperator:k.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:h,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:x},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.groups.findIndex(V=>V.id===y.id),z=k.groups.findIndex(V=>V.id===T.id);F!==-1&&z!==-1&&j(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.groups.map(I=>w(I,O+1,k.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},k.id):e.jsx(Ri,{group:k,depth:O,parentGroupId:A,onUpdateGroupOperator:g,onUpdateGroupNegate:p,onRemoveGroup:m,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:h,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:x},k.id),L=Cn(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:k=>N(!!k)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Oi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Fi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var x;const[o,l]=M.useState(null),c=s.useEditorStore(g=>g.card),i=(x=c==null?void 0:c.config)==null?void 0:x.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=M.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(p=>p.id===g)?"source":n("groupBy").find(p=>p.id===g)?"groupBy":n("metrics").find(p=>p.id===g)?"metrics":n("pivotBy").find(p=>p.id===g)?"pivotBy":n("sortBy").find(p=>p.id===g)?"sortBy":null,[a,n]),h=M.useCallback(g=>{l(g.active.id)},[]),m=M.useCallback(g=>{const{active:p,over:v}=g;if(!v||!t){l(null);return}const j=p.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!bn(w,E.qualifiedEntityName,i)){Ds(),l(null);return}}else{Ds(),l(null);return}}const N=n(R);if(Es(E,N)){l(null);return}const D=s.getNewField(E,R);l(null),r(R,[...N,D]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const D=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Es(N,S)||r(R,[...S,D]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,D]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(D=>D.id===j),N=E.findIndex(D=>D.id===b);if(S!==N){const D=s.arrayMove(E,S,N);r(C,D)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:h,handleDragEnd:m}}function zi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(x=>x.isDevMode),o=s.useEditorStore(x=>x.card);s.isExplorerCard(o);const{config:l}=M.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(x=>x.showAIDialog),u=s.useEditorStore(x=>x.frame),h=s.useManagementStore(x=>x.selectedVisual),m=(h==null?void 0:h.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Us,{}),n&&!m&&e.jsx(_s,{variant:"default"}),m&&e.jsx(Kr,{}),a&&s.isDevEnv]})]})}function Pi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Vi=[{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 _i(){var d,u;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[o,l]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},i=h=>{const m=h.target.value;l(m),m&&!isNaN(parseInt(m))&&a(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Vi.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Ui({isOpen:t,onClose:a}){const n=qt(a,{enabled:t}),r=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.url)||""}),o=s.useEditorStore(h=>h.card),l=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.pluginChartType)||""}),c=s.useEditorStore(h=>{var m;return((m=h.card.customCardPreferences)==null?void 0:m.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function $i({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:h,columnsLoading:m,columnsError:f}){var O;const x=s.useEditorStore(A=>A.card),g=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:p}=s.useEditorActions(),v=s.useEditorStore(A=>A.showAIDialog),[j,b]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:D}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":f?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!x.config)return;if(!A.length){p(x.id,{...x.config,sortByColumns:[]});return}const I=x.config,y=A.map(({id:T,desc:F})=>{var Y,W;const z=(Y=I.metricColumns)==null?void 0:Y.find(_=>_.label===T),V=(W=I.groupByColumns)==null?void 0:W.find(_=>_.label===T),P=z||V;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(T=>T!==null);p(x.id,{...I,sortByColumns:y})},k=M.useMemo(()=>{var A,I;return(I=(A=x.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=x.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(zi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(un,{variant:"outline"}),e.jsx(Pi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(_i,{})}),v&&e.jsx(ds,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(mn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(Na,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||D?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(hn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||D)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:k})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(nn,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx(Ui,{isOpen:j,onClose:()=>b(!1)})]})]})}function qi({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Nn,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Gi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var _,$;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[o,l]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:h}=s.useEditorActions(),m=s.useEditorStore(q=>q.card.type);M.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},x=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},p=()=>{l(!0)},v=q=>{h(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:D=[],isLoading:w,error:L}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:A,setFieldsForContainer:I}=Ys(O),{activeField:y,handleDragStart:T,handleDragEnd:F}=Fi({activeCardId:j.activeCardId,sourceFields:D,getFieldsForContainer:A,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},V=q=>{var U;E(q,{config:{...(U=j.cards.find(H=>H.id===q))==null?void 0:U.config,filters:void 0}})},P=D,Y=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(H=>{U+=Y(H)}),U},W=Y(((_=O==null?void 0:O.config)==null?void 0:_.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(di,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(vi,{selectedChart:m,onChartChange:v,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($i,{selectedChart:m,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:x,onAdvancedToggle:g,onFiltersClick:p,filterCount:W,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:V,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(qi,{activeField:y||null})})]})}function Ki({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:m,handleDragStart:f,handleDragCancel:x,sensors:g}=Rr();M.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function p(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(sn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(gt,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(gt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:m,onDragOver:h,onDragCancel:x,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Qi(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ki,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(sn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Yi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Xi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Yi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function Zi(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function el({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(Zi,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Tr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Qi,{}),e.jsx(Xi,{})]})]})]})]})})}exports.DashboardPlus=el;exports.ResourceManagementPanel=Zt;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Lt;exports.downloadPdf=Ot;exports.getDashbaordStateWithoutData=Bs;
422
+ ON ${O}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(k=>!k.source.name||!k.target.name||!k.operator))))}}function ri({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:p,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:E,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:D,isValidConfiguration:w}=ai({initialJoinPlan:t,availableDataSources:a}),L=k=>{const O=c.find(A=>A.entityName===k);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:k=>{const O=a.find(A=>A.name===k);u({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:k,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(k=>{const O=a.find(y=>y.name===k.source.name),A=a.find(y=>y.name===k.target.name),I=d.has(k.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,O&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(k.id),disabled:k.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(k.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:k.source.name,onValueChange:y=>{const T=a.find(F=>F.name===y);f(k.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(k.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:y=>f(k.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:k.target.name,onValueChange:y=>{const T=a.find(F=>F.name===y);f(k.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?j(k.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),k.source.name&&k.target.name&&O&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:k.joinKeyGroups.map((y,T)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",T+1]}),T>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>C(k.id,T,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(k.id,T),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>S(k.id,T,z,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(k.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>S(k.id,T,z,"operator",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:_=>S(k.id,T,z,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(k.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(k.id,T,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(k.id,T),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function jt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(ri,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function oi({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,i)=>c.sequence-i.sequence),l=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=n.find(d=>d.name===o.source.name),i=n.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ii(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=M.useState(!1),l=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),o(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const f=[...n.joins].sort((x,v)=>x.sequence-v.sequence),p=n.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
423
+ FROM ${p.name}`;return f.forEach(x=>{const v=l.find(C=>C.name===x.target.name);if(!v)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(E=>{var S,N,D,w;return((S=E.source)==null?void 0:S.name)&&((N=E.target)==null?void 0:N.name)&&((D=E.source)==null?void 0:D.entityName)&&((w=E.target)==null?void 0:w.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
424
+ ${x.joinType} JOIN ${v.name}
425
+ ON ${b}`}),g};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(oi,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(jt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function li({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function ci({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function di({isVisible:t,onToggleVisibility:a}){s.useEditorStore(m=>m.isDevMode),s.useEditorStore(m=>m.card.connectionId),s.useDashboardStore(m=>m.isVisualEditing);const[n,r]=M.useState(!1),[o,l]=M.useState(!0),c=s.useEditorStore(m=>m.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!o}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(!o),className:"h-6 w-6 p-0",children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((m,h)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(m),e.jsx("button",{onClick:f=>{f.stopPropagation();const p=u.selectedEntities.filter(g=>!(g.name===m.name&&g.type===m.type));i({...d,...c,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(li,{entity:m})]},`${m.type}-${m.name}-${h}`)),u.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})}),e.jsx(ci,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(ii,{})]})]}),e.jsx(ni,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Xe=[{id:"table",icon:ls,label:"Table"},{id:"bar",icon:rs,label:"Bar Chart"},{id:"line",icon:os,label:"Line Chart"},{id:"area",icon:wt,label:"Area Chart"},{id:"stackedBar",icon:Ts,label:"Stacked Bar Chart"},{id:"combo",icon:Qn,label:"Combo Chart"},{id:"stackedLine",icon:Ks,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:is,label:"Pie Chart"},{id:"doughnut",icon:Ms,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Rs,label:"Radar Chart"},{id:"polarArea",icon:qs,label:"Polar Area Chart"},{id:"tornado",icon:Os,label:"Tornado Chart"},{id:"range",icon:Is,label:"Range Chart"},{id:"kpi",icon:Qs,label:"KPI"},{id:"text",icon:Ct,label:"Text"},{id:"map",icon:Ls,label:"Map"}],Xs=t=>{const a=t.toLowerCase();for(const n of Xe)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},ui="chart-selector-standard-first";function mi(){const[t,a]=s.useLocalStorageState(ui,!0);return{standardFirst:t,updatePreference:a}}const yt=({pluginVisual:t,index:a,onSelect:n})=>{const r=us(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Xs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},vt=["default","standardPlugin","customPlugin"];function hi({selectedChart:t,onChartChange:a}){var S;const[n,r]=M.useState([]),[o,l]=M.useState(!1),{data:c}=$s();mi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";Fs(d);const{setCardType:u,setCardPreferences:m,setIsDevMode:h}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:p,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>x?[x,...vt.filter(N=>N!==x)]:vt,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(k){return console.error(`Failed to load manifest for plugin ${L.label}`,k),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),m({}),u(N),["custom","text","map"].includes(N)&&(h(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),m({}),u("custom"),p({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var D;if(t==="custom"){const w=s.useEditorStore.getState().card;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=Xe.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var D,w;if(t==="custom"){const L=s.useEditorStore.getState().card,k=(D=L==null?void 0:L.customCardPreferences)==null?void 0:D.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(k&&O)return e.jsx(xi,{icon:k,componentName:O});if(O){const A=Xs(O);if(A)return A}return e.jsx($e,{className:"h-4 w-4"})}const N=Xe.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx($e,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:D=>v(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Xe.map(D=>{const w=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>b(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=n.filter(w=>w.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=n.filter(w=>w.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((w,L)=>e.jsx(yt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const xi=({icon:t,componentName:a})=>{const n=us(),r=Xs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx($e,{className:"h-4 w-4"})},Nn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ge,{className:"h-3 w-3"})})};function pi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[o,l]=M.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function fi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[o,l]=M.useState(""),[c,i]=M.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[o]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function bt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function gi({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var et;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),p=s.useEditorStore(X=>X.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:w}=Ys(p),[L,k]=M.useState(!1),[O,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[T,F]=M.useState(!!t.customFormat),[z,_]=M.useState(t.granularity||"day"),[P,Y]=M.useState(t.aliasTemplate||""),[W,V]=M.useState(t.valueAliases||{}),$=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&v(n,X,""))},q=X=>{y(X),a==="groupBy"&&v(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&j(n,X)},H=X=>{Y(X),a==="metrics"&&b(n,X)},Q=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{g(a,n,X)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(m),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",K=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],B=!oe&&a!=="pivotBy",J=se&&a==="groupBy",ie=!oe&&se&&a==="groupBy",ye=oe&&se&&a==="groupBy",ke=oe&&a==="metrics"&&((et=p.config)==null?void 0:et.comparisonType)==="target",ne=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce=()=>B?e.jsx(bt,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,wn=()=>J?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,kn=()=>ie?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:T?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:K.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),T&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:X=>{X.stopPropagation(),q(X.target.value)},onClick:X=>X.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})}):null,Dn=()=>{var X,ve,Re,st,tt;return ye?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=p.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ve=p.config)==null?void 0:ve.showTrendline)||!1,onCheckedChange:S})]})}),((Re=p.config)==null?void 0:Re.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((st=p.config)==null?void 0:st.trendlineWindow)||30,onChange:In=>{const An=parseInt(In.target.value)||30;N(An)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((tt=p.config)==null?void 0:tt.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},En=()=>{var X,ve;return ke?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(bt,{value:((X=p.config)==null?void 0:X.targetValue)!==void 0&&((ve=p.config)==null?void 0:ve.targetValue)!==null?String(p.config.targetValue):"",onSave:Re=>{!isNaN(Number(Re))&&Re!==null?w(Number(Re)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},Tn=()=>ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{x(n,X)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(yn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(pi,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(fi,{valueAliases:W,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Nn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),k(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ve=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ve),o(ve)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),ce(),wn(),kn(),Dn(),En(),Tn()]})]})}function ji({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.card.type),h=a.length>0,f=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const p=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),p&&e.jsx(ji,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(gi,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:m})})},g.id)})})})})]})}function yi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},m=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:m().label,placeholder:m().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function vi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(hi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(ds,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(wa,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(yi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function bi({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=E=>{const S=N=>{if(N.id===E){const D=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=(E,S)=>{const N=D=>D.id===E?{...D,conditions:D.conditions.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},f=(E,S)=>{const N=D=>D.id===E?{...D,groups:D.groups.filter(w=>w.id!==S)}:{...D,groups:D.groups.map(N)};r(N(n))},p=(E,S,N,D)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(k=>k.id===S?{...k,[N]:D}:k)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(D)};r(D(n))},x=(E,S)=>{const N=D=>D.id===E?{...D,logicalOperator:S}:{...D,groups:D.groups.map(N)};r(N(n))},v=(E,S)=>{const N=D=>D.id===E?{...D,negate:S}:{...D,groups:D.groups.map(N)};r(N(n))},j=(E,S,N)=>{const D=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},b=(E,S,N)=>{const D=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(D)};r(D(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=D=>{let w="";typeof D.field=="object"?w=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:w=String(D.field);const L=D.operator;let k=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof k=="string"?k=`'${k}'`:Array.isArray(k)&&(k=`'${k.join(", ")}'`);else if(D.field.dataType==="date")(typeof k=="string"||k instanceof Date)&&(k=`DATE('${k}')`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(k)?O=k.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof k=="string"?O=k.split(",").map(A=>{const I=A.trim();return D.field.dataType==="string"?`'${I}'`:I}):typeof k=="number"&&(O=[String(k)]),k=`(${O.join(", ")})`}switch(L){case"contains":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;case"startsWith":return typeof k=="string"?`${w} LIKE '${k.replace(/'/g,"")}%'`:`${w} LIKE '${String(k)}%'`;case"endsWith":return typeof k=="string"?`${w} LIKE '%${k.replace(/'/g,"")}'`:`${w} LIKE '%${String(k)}'`;default:return`${w} ${L} ${k}`}},N=D=>{const w=D.conditions.map(S),L=D.groups.map(I=>N(I)),k=[...w,...L].filter(Boolean);if(k.length===0)return"";const O=k.join(` ${D.logicalOperator} `),A=k.length>1?`(${O})`:O;return D.negate?`NOT ${A}`:A};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:p,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ni({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Ci=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(na,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Si=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function wi({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return n.forEach(u=>{const m=Si(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ni,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ci(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,p)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+p))]},`${d}-${m}`))},d))})]})})]})}function Zs(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=Zs(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}const Cn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Cn(n)}),a};function Di({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=Zs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ei=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ti=["=","!=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Mi=["=","!=",">",">=","<","<=","in","not in"];function Li(t){switch(t){case"string":return Ti;case"number":return Ii;case"boolean":return Ai;case"date":return Mi;default:return Ei}}function Sn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=Zs(t.field),j={transform:s.CSS.Transform.toString(f),transition:p};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(wi,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Li(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Di,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Ri({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:p,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id){const O=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&u(t.id,O,A)}},D=w=>{const{active:L,over:k}=w;if(k&&L.id!==k.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===k.id);O!==-1&&A!==-1&&m(n,O,A)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Sn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Oi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=bi({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=M.useState(!1),D=(k,O,A)=>{const I=y=>y.id===k?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:A,dataType:A.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(k,O=0,A)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.conditions.findIndex(_=>_.id===y.id),z=k.conditions.findIndex(_=>_.id===T.id);F!==-1&&z!==-1&&v(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.conditions.map((I,y)=>e.jsx(Sn,{condition:I,index:y,groupId:k.id,groupLogicalOperator:k.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:p},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const F=k.groups.findIndex(_=>_.id===y.id),z=k.groups.findIndex(_=>_.id===T.id);F!==-1&&z!==-1&&j(k.id,F,z)}},children:e.jsx(s.SortableContext,{items:k.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:k.groups.map(I=>w(I,O+1,k.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},k.id):e.jsx(Ri,{group:k,depth:O,parentGroupId:A,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:p},k.id),L=Cn(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:k=>N(!!k)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Oi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Fi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var p;const[o,l]=M.useState(null),c=s.useEditorStore(g=>g.card),i=(p=c==null?void 0:c.config)==null?void 0:p.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=M.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),m=M.useCallback(g=>{l(g.active.id)},[]),h=M.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){l(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!bn(w,E.qualifiedEntityName,i)){Ds(),l(null);return}}else{Ds(),l(null);return}}const N=n(R);if(Es(E,N)){l(null);return}const D=s.getNewField(E,R);l(null),r(R,[...N,D]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const D=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Es(N,S)||r(R,[...S,D]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,D]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(D=>D.id===j),N=E.findIndex(D=>D.id===b);if(S!==N){const D=s.arrayMove(E,S,N);r(C,D)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:m,handleDragEnd:h}}function zi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(p=>p.isDevMode),o=s.useEditorStore(p=>p.card);s.isExplorerCard(o);const{config:l}=M.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(p=>p.showAIDialog),u=s.useEditorStore(p=>p.frame),m=s.useManagementStore(p=>p.selectedVisual),h=(m==null?void 0:m.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Us,{}),n&&!h&&e.jsx(Vs,{variant:"default"}),h&&e.jsx(Kr,{}),a&&s.isDevEnv]})]})}function Pi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const _i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Vi(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[o,l]=M.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:_i.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Ui({isOpen:t,onClose:a}){const n=qt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function $i({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var O;const p=s.useEditorStore(A=>A.card),g=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(A=>A.showAIDialog),[j,b]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:D}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(p.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const L=A=>{if(!p.config)return;if(!A.length){x(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,y=A.map(({id:T,desc:F})=>{var Y,W;const z=(Y=I.metricColumns)==null?void 0:Y.find(V=>V.label===T),_=(W=I.groupByColumns)==null?void 0:W.find(V=>V.label===T),P=z||_;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(T=>T!==null);x(p.id,{...I,sortByColumns:y})},k=M.useMemo(()=>{var A,I;return(I=(A=p.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=p.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(zi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(un,{variant:"outline"}),e.jsx(Pi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Vi,{})}),v&&e.jsx(ds,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(mn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(Na,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||D?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(hn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||D)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:k})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(nn,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx(Ui,{isOpen:j,onClose:()=>b(!1)})]})]})}function qi({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Nn,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Gi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var V,$;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[o,l]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);M.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},p=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},v=q=>{m(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:D=[],isLoading:w,error:L}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:A,setFieldsForContainer:I}=Ys(O),{activeField:y,handleDragStart:T,handleDragEnd:F}=Fi({activeCardId:j.activeCardId,sourceFields:D,getFieldsForContainer:A,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},_=q=>{var U;E(q,{config:{...(U=j.cards.find(H=>H.id===q))==null?void 0:U.config,filters:void 0}})},P=D,Y=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(H=>{U+=Y(H)}),U},W=Y(((V=O==null?void 0:O.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(di,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(vi,{selectedChart:h,onChartChange:v,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($i,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:p,onAdvancedToggle:g,onFiltersClick:x,filterCount:W,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:_,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(qi,{activeField:y||null})})]})}function Ki({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:p,sensors:g}=Rr();M.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function x(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(sn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(gt,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(gt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Qi(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Ki,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=gn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(sn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Yi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Xi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Yi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function Zi(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function el({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(Zi,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Tr,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Qi,{}),e.jsx(Xi,{})]})]})]})]})})}exports.DashboardPlus=el;exports.ResourceManagementPanel=Zt;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Lt;exports.downloadPdf=Ot;exports.getDashbaordStateWithoutData=Bs;