react-semaphor 0.0.497 → 0.0.498

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 Ot=s=>{throw TypeError(s)};var Je=(s,a,n)=>a.has(s)||Ot("Cannot "+n);var W=(s,a,n)=>(Je(s,a,"read from private field"),n?n.call(s):a.get(s)),oe=(s,a,n)=>a.has(s)?Ot("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(s):a.set(s,n),te=(s,a,n,r)=>(Je(s,a,"write to private field"),r?r.call(s,n):a.set(s,n),n),ie=(s,a,n)=>(Je(s,a,"access private method"),n);const e=require("react/jsx-runtime"),t=require("./index-DS0Y6nR1.js"),L=require("react");require("react-dom");function Ls(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const re=Ls(L);function Ft(s,a){return s.filter(n=>!a.includes(n))}function Os(s,a,n){const r=s.slice(0);return r[a]=n,r}var xe,ne,ve,Ce,ae,me,Ee,Ie,De,ee,tt,st,nt,at,rt,Ht,Fs=(Ht=class extends t.Subscribable{constructor(a,n,r){super();oe(this,ee);oe(this,xe);oe(this,ne);oe(this,ve);oe(this,Ce);oe(this,ae);oe(this,me);oe(this,Ee);oe(this,Ie);oe(this,De,[]);te(this,xe,a),te(this,Ce,r),te(this,ve,[]),te(this,ae,[]),te(this,ne,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&W(this,ae).forEach(a=>{a.subscribe(n=>{ie(this,ee,at).call(this,a,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,W(this,ae).forEach(a=>{a.destroy()})}setQueries(a,n,r){if(te(this,ve,a),te(this,Ce,n),process.env.NODE_ENV!=="production"){const o=a.map(i=>W(this,xe).defaultQueryOptions(i).queryHash);new Set(o).size!==o.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}t.notifyManager.batch(()=>{const o=W(this,ae),i=ie(this,ee,nt).call(this,W(this,ve));te(this,De,i),i.forEach(h=>h.observer.setOptions(h.defaultedQueryOptions,r));const l=i.map(h=>h.observer),u=l.map(h=>h.getCurrentResult()),c=l.some((h,d)=>h!==o[d]);o.length===l.length&&!c||(te(this,ae,l),te(this,ne,u),this.hasListeners()&&(Ft(o,l).forEach(h=>{h.destroy()}),Ft(l,o).forEach(h=>{h.subscribe(d=>{ie(this,ee,at).call(this,h,d)})}),ie(this,ee,rt).call(this)))})}getCurrentResult(){return W(this,ne)}getQueries(){return W(this,ae).map(a=>a.getCurrentQuery())}getObservers(){return W(this,ae)}getOptimisticResult(a,n){const r=ie(this,ee,nt).call(this,a),o=r.map(i=>i.observer.getOptimisticResult(i.defaultedQueryOptions));return[o,i=>ie(this,ee,st).call(this,i??o,n),()=>ie(this,ee,tt).call(this,o,r)]}},xe=new WeakMap,ne=new WeakMap,ve=new WeakMap,Ce=new WeakMap,ae=new WeakMap,me=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,De=new WeakMap,ee=new WeakSet,tt=function(a,n){return n.map((r,o)=>{const i=a[o];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,l=>{n.forEach(u=>{u.observer.trackProp(l)})})})},st=function(a,n){return n?((!W(this,me)||W(this,ne)!==W(this,Ie)||n!==W(this,Ee))&&(te(this,Ee,n),te(this,Ie,W(this,ne)),te(this,me,t.replaceEqualDeep(W(this,me),n(a)))),W(this,me)):a},nt=function(a){const n=new Map(W(this,ae).map(o=>[o.options.queryHash,o])),r=[];return a.forEach(o=>{const i=W(this,xe).defaultQueryOptions(o),l=n.get(i.queryHash);l?r.push({defaultedQueryOptions:i,observer:l}):r.push({defaultedQueryOptions:i,observer:new t.QueryObserver(W(this,xe),i)})}),r},at=function(a,n){const r=W(this,ae).indexOf(a);r!==-1&&(te(this,ne,Os(W(this,ne),r,n)),ie(this,ee,rt).call(this))},rt=function(){var a;if(this.hasListeners()){const n=W(this,me),r=ie(this,ee,tt).call(this,W(this,ne),W(this,De)),o=ie(this,ee,st).call(this,r,(a=W(this,Ce))==null?void 0:a.combine);n!==o&&t.notifyManager.batch(()=>{this.listeners.forEach(i=>{i(W(this,ne))})})}},Ht);function zs({queries:s,...a},n){const r=t.useQueryClient(),o=t.useIsRestoring(),i=t.useQueryErrorResetBoundary(),l=re.useMemo(()=>s.map(m=>{const v=r.defaultQueryOptions(m);return v._optimisticResults=o?"isRestoring":"optimistic",v}),[s,r,o]);l.forEach(m=>{t.ensureSuspenseTimers(m),t.ensurePreventErrorBoundaryRetry(m,i)}),t.useClearResetErrorBoundary(i);const[u]=re.useState(()=>new Fs(r,l,a)),[c,h,d]=u.getOptimisticResult(l,a.combine),x=!o&&a.subscribed!==!1;re.useSyncExternalStore(re.useCallback(m=>x?u.subscribe(t.notifyManager.batchCalls(m)):t.noop,[u,x]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),re.useEffect(()=>{u.setQueries(l,a,{listeners:!1})},[l,a,u]);const p=c.some((m,v)=>t.shouldSuspend(l[v],m))?c.flatMap((m,v)=>{const f=l[v];if(f){const k=new t.QueryObserver(r,f);if(t.shouldSuspend(f,m))return t.fetchOptimistic(f,k,i);t.willFetch(m,o)&&t.fetchOptimistic(f,k,i)}return[]}):[];if(p.length>0)throw Promise.all(p);const g=c.find((m,v)=>{const f=l[v];return f&&t.getHasError({result:m,errorResetBoundary:i,throwOnError:f.throwOnError,query:r.getQueryCache().get(f.queryHash),suspense:f.suspense})});if(g!=null&&g.error)throw g.error;return h(d())}/**
1
+ "use strict";var Ot=s=>{throw TypeError(s)};var Je=(s,a,n)=>a.has(s)||Ot("Cannot "+n);var W=(s,a,n)=>(Je(s,a,"read from private field"),n?n.call(s):a.get(s)),oe=(s,a,n)=>a.has(s)?Ot("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(s):a.set(s,n),te=(s,a,n,r)=>(Je(s,a,"write to private field"),r?r.call(s,n):a.set(s,n),n),ie=(s,a,n)=>(Je(s,a,"access private method"),n);const e=require("react/jsx-runtime"),t=require("./index-DMXY0DgW.js"),L=require("react");require("react-dom");function Ls(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const re=Ls(L);function Ft(s,a){return s.filter(n=>!a.includes(n))}function Os(s,a,n){const r=s.slice(0);return r[a]=n,r}var pe,ne,Ce,Ne,ae,he,Ie,De,Te,ee,tt,st,nt,at,rt,Ht,Fs=(Ht=class extends t.Subscribable{constructor(a,n,r){super();oe(this,ee);oe(this,pe);oe(this,ne);oe(this,Ce);oe(this,Ne);oe(this,ae);oe(this,he);oe(this,Ie);oe(this,De);oe(this,Te,[]);te(this,pe,a),te(this,Ne,r),te(this,Ce,[]),te(this,ae,[]),te(this,ne,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&W(this,ae).forEach(a=>{a.subscribe(n=>{ie(this,ee,at).call(this,a,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,W(this,ae).forEach(a=>{a.destroy()})}setQueries(a,n,r){if(te(this,Ce,a),te(this,Ne,n),process.env.NODE_ENV!=="production"){const o=a.map(i=>W(this,pe).defaultQueryOptions(i).queryHash);new Set(o).size!==o.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}t.notifyManager.batch(()=>{const o=W(this,ae),i=ie(this,ee,nt).call(this,W(this,Ce));te(this,Te,i),i.forEach(h=>h.observer.setOptions(h.defaultedQueryOptions,r));const l=i.map(h=>h.observer),u=l.map(h=>h.getCurrentResult()),c=l.some((h,d)=>h!==o[d]);o.length===l.length&&!c||(te(this,ae,l),te(this,ne,u),this.hasListeners()&&(Ft(o,l).forEach(h=>{h.destroy()}),Ft(l,o).forEach(h=>{h.subscribe(d=>{ie(this,ee,at).call(this,h,d)})}),ie(this,ee,rt).call(this)))})}getCurrentResult(){return W(this,ne)}getQueries(){return W(this,ae).map(a=>a.getCurrentQuery())}getObservers(){return W(this,ae)}getOptimisticResult(a,n){const r=ie(this,ee,nt).call(this,a),o=r.map(i=>i.observer.getOptimisticResult(i.defaultedQueryOptions));return[o,i=>ie(this,ee,st).call(this,i??o,n),()=>ie(this,ee,tt).call(this,o,r)]}},pe=new WeakMap,ne=new WeakMap,Ce=new WeakMap,Ne=new WeakMap,ae=new WeakMap,he=new WeakMap,Ie=new WeakMap,De=new WeakMap,Te=new WeakMap,ee=new WeakSet,tt=function(a,n){return n.map((r,o)=>{const i=a[o];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,l=>{n.forEach(u=>{u.observer.trackProp(l)})})})},st=function(a,n){return n?((!W(this,he)||W(this,ne)!==W(this,De)||n!==W(this,Ie))&&(te(this,Ie,n),te(this,De,W(this,ne)),te(this,he,t.replaceEqualDeep(W(this,he),n(a)))),W(this,he)):a},nt=function(a){const n=new Map(W(this,ae).map(o=>[o.options.queryHash,o])),r=[];return a.forEach(o=>{const i=W(this,pe).defaultQueryOptions(o),l=n.get(i.queryHash);l?r.push({defaultedQueryOptions:i,observer:l}):r.push({defaultedQueryOptions:i,observer:new t.QueryObserver(W(this,pe),i)})}),r},at=function(a,n){const r=W(this,ae).indexOf(a);r!==-1&&(te(this,ne,Os(W(this,ne),r,n)),ie(this,ee,rt).call(this))},rt=function(){var a;if(this.hasListeners()){const n=W(this,he),r=ie(this,ee,tt).call(this,W(this,ne),W(this,Te)),o=ie(this,ee,st).call(this,r,(a=W(this,Ne))==null?void 0:a.combine);n!==o&&t.notifyManager.batch(()=>{this.listeners.forEach(i=>{i(W(this,ne))})})}},Ht);function zs({queries:s,...a},n){const r=t.useQueryClient(),o=t.useIsRestoring(),i=t.useQueryErrorResetBoundary(),l=re.useMemo(()=>s.map(m=>{const v=r.defaultQueryOptions(m);return v._optimisticResults=o?"isRestoring":"optimistic",v}),[s,r,o]);l.forEach(m=>{t.ensureSuspenseTimers(m),t.ensurePreventErrorBoundaryRetry(m,i)}),t.useClearResetErrorBoundary(i);const[u]=re.useState(()=>new Fs(r,l,a)),[c,h,d]=u.getOptimisticResult(l,a.combine),x=!o&&a.subscribed!==!1;re.useSyncExternalStore(re.useCallback(m=>x?u.subscribe(t.notifyManager.batchCalls(m)):t.noop,[u,x]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),re.useEffect(()=>{u.setQueries(l,a,{listeners:!1})},[l,a,u]);const p=c.some((m,v)=>t.shouldSuspend(l[v],m))?c.flatMap((m,v)=>{const f=l[v];if(f){const k=new t.QueryObserver(r,f);if(t.shouldSuspend(f,m))return t.fetchOptimistic(f,k,i);t.willFetch(m,o)&&t.fetchOptimistic(f,k,i)}return[]}):[];if(p.length>0)throw Promise.all(p);const j=c.find((m,v)=>{const f=l[v];return f&&t.getHasError({result:m,errorResetBoundary:i,throwOnError:f.throwOnError,query:r.getQueryCache().get(f.queryHash),suspense:f.suspense})});if(j!=null&&j.error)throw j.error;return h(d())}/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -388,7 +388,7 @@
388
388
  *
389
389
  * This source code is licensed under the ISC license.
390
390
  * See the LICENSE file in the root directory of this source tree.
391
- */const Zt=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function Ct(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(l=>es(l))}})}})}}function es(s){return{...s,customCfg:On(s.customCfg),data:[]}}function On(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Fn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function ot(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:l}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:l,operation:"update"})}async function zn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Bn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(m=>m.lenses),{setLenses:i,setSelectedLensId:l}=t.useDashboardActions(),[u,c]=L.useState(!1),[h,d]=L.useState(!1),x=t.useDashboardStore(m=>m.dashboard),j=t.useDashboardStore(m=>m.filterValues),{authToken:p}=t.useSemaphorContext();async function g(){c(!0);const m=Ct(x),v=await Fn(s,m,j,p==null?void 0:p.accessToken);v&&(i([...o||[],v]),l(v.id),d(!1)),c(!1)}return e.jsxs(t.Dialog,{open:h,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.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(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:m=>{a(m.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(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:u,children:u?"Creating...":"Add"})})]})]})}function Rn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(d=>d.lenses),r=t.useDashboardStore(d=>d.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:l}=t.useSemaphorContext();async function u(d){i(d)}async function c(d){if(await zn(d,l==null?void 0:l.accessToken)){const j=n==null?void 0:n.filter(p=>p.id!==d);o(j||[]),i("original")}}async function h(d){const x=n==null?void 0:n.map(g=>g.id===d.id?{...g,isDefault:!d.isDefault}:{...g,isDefault:!1});o(x||[]);const j={...d,isDefault:!d.isDefault};await ot(j,l==null?void 0:l.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==d.id){const g={...p,isDefault:!1};await ot(g,l==null?void 0:l.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(hn,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:u,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(d=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:d.id,children:[e.jsx("p",{children:d.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(fn,{onClick:x=>{x.preventDefault(),h(d)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!d.isDefault,"text-green-500":d.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:x=>{x.preventDefault(),c(d.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},d.id))]})]})]})}function ts(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function ss(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=ts();if(s)return;const l=new URLSearchParams;l.set("token",(a==null?void 0:a.accessToken)||""),l.set("theme",n),l.set("filterValues",JSON.stringify(r)),l.set("selectedSheetId",i||"");const u=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(l.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const d=(await(await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,x=document.createElement("a");x.href=d;const j=`${o}-${new Date().toISOString()}.pdf`;x.download=j,x.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function Pn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await ss()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(ce,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function le({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:l,showPlaceholderLabel:u=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),u&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))]})})]})}const Rt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function ns({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:l}=Vn(),[u,c]=L.useState(""),[h,d]=L.useState(Rt[0].value),[x,j]=L.useState("06:00"),[p,g]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(tn,{className:"size-4"})})}),e.jsx(t.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(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:u,onChange:m=>c(m.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:m=>{g(m.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(le,{className:"col-span-2 h-8",label:"Select Frequency",options:Rt,value:h,onValueChange:m=>d(m)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:x,onChange:m=>j(m.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:u,frequency:h,time:x,subject:p}),j("00:00"),c(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!u,children:[o==="loading"&&e.jsx(ce,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Ut,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.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"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(m=>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:[t.titleCase(m.frequency)," "]}),e.jsx(t.Label,{children:m.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Pt,{tooltip:`Next Run: ${new Date(m.nextRun).toLocaleString()} ${m.timezone}`,children:e.jsx(en,{className:"size-3.5"})}),e.jsx(Pt,{tooltip:`${m.endUserEmail}`,children:e.jsx(Cn,{className:"size-3.5"})}),l===m.id?e.jsx(ce,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(m.id),className:"size-3.5 cursor-pointer"})]})]},m.id))})]})]})]})})]})})}const Pt=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function Vn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),l=t.useDashboardStore(T=>T.authToken),u=t.useDashboardStore(T=>T.dashboard.id),c=t.useDashboardStore(T=>T.dashboard.title),{endUserId:h}=t.getTenantAndEndUserId((l==null?void 0:l.accessToken)||""),d="https://semaphor.cloud/api/v1/subscriptions/get",x={dashboardId:u,endUserId:h},{data:j,isLoading:p,isError:g,isFetching:m,refetch:v}=t.useQuery({queryKey:["subscriptions",u,h],queryFn:()=>t.getRequest(d,(l==null?void 0:l.accessToken)||"",x),enabled:!!(l!=null&&l.accessToken)&&!!u&&!!h});async function f({email:T,subject:E,frequency:y,time:C}){const{authToken:b,...w}=ts(),I=Intl.DateTimeFormat().resolvedOptions().timeZone,D={email:T,frequency:y,time:C,timezone:I,endUserId:h,endUserEmail:T,subject:E||c||"Scheduled Dashboard",dashboardId:u,dashboardParams:w};a("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const F=await t.postRequestRegular(S,(b==null?void 0:b.accessToken)||"",{...D});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(F){console.error(F),a("error"),r(F.message)}}async function k(T){const E="https://semaphor.cloud/api/v1/subscriptions/delete";i(T);try{await t.postRequestRegular(E,(l==null?void 0:l.accessToken)||"",{id:T}),v(),setTimeout(()=>{i(null)},2e3)}catch(y){console.error(y),i(null),a("error"),r(y.message)}}return{data:j,isLoading:p,isFetching:m,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:f,handleDeleteSubscription:k,status:s,error:n}}function qn(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(D=>D.theme);const a=t.useDashboardStore(D=>D.lenses),n=t.useDashboardStore(D=>D.selectedLensId),r=a==null?void 0:a.find(D=>D.id===n),o=t.useDashboardStore(D=>D.dashboard);t.useDashboardStore(D=>D.selectedSheetId);const i=t.useDashboardStore(D=>D.isDashboardEditing),l=t.useEditorStore(D=>D.selectedConnectionId),[u,c]=L.useState(!1),h=t.useDashboardStore(D=>D.filterValues),d=t.useDashboardStore(D=>D.isVisualEditing),x=t.useDashboardStore(D=>D.showFilters);t.useDashboardStore(D=>D.showDashboardJSON);const j=t.useDashboardStore(D=>D.onSaveFunction),p=t.useDashboardStore(D=>D.actions.setShowFilters),{addFrame:g,setSelectedFrameId:m}=t.useDashboardStore(D=>D.actions),{getSelectedSheet:v,setIsDashboardEditing:f,setShowDashboardJSON:k}=t.useDashboardStore(D=>D.actions),T=v(),{tenantId:E,endUserId:y}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),C=L.useMemo(()=>E||y,[E,y]),b=()=>{if(!i||!T)return;const D={connectionId:l,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},S={id:t.v4(),cards:[D],activeCardId:D.id};g(T.id,S),m(S.id)},w=()=>{f(!0)};async function I(){if(c(!0),!n||!r)return;const D=Ct(o),S=JSON.stringify(D),F={...r,template:S,filterValues:h};await ot(F,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),j==null||j(D),c(!1)}return d?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!d&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!d&&e.jsx(Pn,{}),!d&&e.jsx(ns,{}),i&&!d&&C&&e.jsx(Bn,{}),!d&&C&&e.jsx(Rn,{}),i&&!d&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:b,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!d&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{f(!1),k(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!d&&C&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:I,size:"sm",children:e.jsx(Tn,{className:"h-4 w-4"})}),!x&&!d&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>p(!0),size:"sm",children:e.jsx(ft,{className:"h-4 w-4"})}),!d&&i&&!1,!d&&!1]})]})}function _n({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:l,className:u,icon:c,showNone:h=!1}){const d=re.useRef(null),[x,j]=re.useState(!1),[p,g]=re.useState("100%"),m=h?[...a||[],{id:"none",name:"None"}]:a;re.useLayoutEffect(()=>{d.current&&g(d.current.offsetWidth)},[]);function v(){var k;return o?"Loading...":i?"Error":n?(k=a==null?void 0:a.find(T=>T.id===n))==null?void 0:k.name:`Select ${s}`}function f(k,T){r(T),j(!1)}return e.jsxs(t.Popover,{open:x,onOpenChange:j,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:d,variant:"outline",role:"combobox","aria-expanded":x,className:t.cn("flex h-9 w-full justify-between",u),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("div",{className:"mr-2",children:c}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:p},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:l,children:e.jsx(Kt,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:m==null?void 0:m.map(k=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:k.name,onSelect:T=>f(T,k.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===k.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:k.name,children:k.name})]})},k.id))})]})]})})]})}function be({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:l,showNone:u=!1,className:c,disabled:h=!1,type:d="combobox"}){const x=r?"Loading...":o?"Error":n;function j(){if(s==="Connection")return e.jsx(In,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(kn,{className:"size-4"});if(s==="Table")return e.jsx(He,{className:"size-4"});if(s==="Model")return e.jsx(Ks,{className:"size-4"})}function p(){return e.jsxs(t.Select,{disabled:h,value:x,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",c),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(Kt,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[u&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((m,v)=>e.jsx(t.SelectItem,{value:m.id,children:m.name},v))]}),(r||o)&&e.jsx(t.SelectItem,{value:x,children:x})]})})]})}function g(){return e.jsx(_n,{icon:j(),items:a,value:x,onChange:l||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:u})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:d==="select"?p():g()})})}function Gn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(m=>m.selectedTableName),o=t.useEditorStore(m=>m.selectedSchemaName),i=t.useEditorStore(m=>m.selectedDatabaseName),l=t.useEditorStore(m=>m.selectedDatamodelId),u=t.useEditorStore(m=>m.sqlGen),{modelItems:c,connectionType:h}=t.useEditorAside(),d=t.useEditorStore(m=>m.actions.setSqlGen),x=t.useEditorStore(m=>m.actions.setCardSql),j=t.useEditorStore(m=>m.actions.setRunSql);function p(m,v){var E;const f=t.createSqlGenConfig(m,u,v),k=(E=c==null?void 0:c.find(y=>y.id===l))==null?void 0:E.name;d(f);const T=t.getSql(f,t.fmt(o||""),t.fmt(r),k||"",h,i||"");T&&(x(T),j(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Nt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(gt,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Xt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Qs,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Ue({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Nt,{column:s}),e.jsx("span",{children:s.column_name})]})}function $n({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:l}=t.useDraggable({id:s,data:{type:n}}),u=l?{translate:t.CSS.Translate.toString(l),transform:t.CSS.Transform.toString(l)}:void 0;return e.jsx("div",{ref:i,style:u,...o,...r,children:a})}function Hn({onClick:s,column:a}){const n=t.useDndStore(d=>d.activeId),r=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.groupByColumns}),o=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.metricColumns}),i=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.filterColumns});function l(d){return u(d)||c(d)||h(d)}function u(d){return r==null?void 0:r.some(x=>x.name===d.column_name)}function c(d){return o==null?void 0:o.some(x=>x.name===d.column_name)}function h(d){return i==null?void 0:i.some(x=>x.name===d.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":l(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Ue,{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(Ue,{column:a})}),e.jsx($n,{id:a.column_name,type:"column",children:e.jsx(Ue,{column:a})})]})}const Ye={id:"__placeholder__",role:"groupby",type:"string"},Ke={id:"__placeholder__",role:"groupby",type:"string"},Qe={id:"__placeholder__",role:"metric",type:"number"},We={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},as={id:"__placeholder__"},pe="droppable-group-by",fe="droppable-metrics",ge="droppable-pivot-by",ze="sortable-group-by",it="sortable-metrics",Be="sortable-pivot-by",lt="droppable-filters",ct="sortable-filters",St="sortable-order-by";function Jn(){const s=t.useDndStore(A=>A.insertIndex),a=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.groupByColumns)||[]}),n=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.metricColumns)||[]}),r=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.filterColumns)||[]}),o=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.orderBy)||[]}),i=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.pivotColumns)||[]}),{setInsertIndex:l,setActiveId:u,setPreviewGroupByColumns:c,setPreviewMetricColumns:h,setPreviewFilterColumns:d,setPreviewPivotColumns:x}=t.useDndActions(),{setGroupByColumns:j,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:m,setPivotByColumns:v}=t.useEditorActions(),{columns:f}=t.useDataColumns(),{formattedTableName:k}=t.useEditorAside(),T=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),E=A=>{var z;const{active:N,over:M}=A;if(((z=N.data.current)==null?void 0:z.type)==="column"&&M){const R=M.id,q=f.find($=>$.column_name===N.id);if(!q)return;const B=t.isNumberDataType(q.data_type),K=t.isTextDataType(q.data_type),J=t.isDateDataType(q.data_type);if(K||J){if(a.some(U=>U.id===R)){const U=a.findIndex(V=>V.id===R);l(U);const G=a.filter(V=>V.id!==Ye.id);G.splice(U,0,Ye),c(G)}else if(M.id===pe){l(a.length);const U=[...a,Ye];c(U),h(n),d(r)}}if(K||J){if(i.some(U=>U.id===R)){const U=i.findIndex(V=>V.id===R);l(U);const G=i.filter(V=>V.id!==Ke.id);G.splice(U,0,Ke),x(G)}else if(M.id===ge){l(i.length);const U=[...i,Ke];x(U),c(a),h(n),d(r)}}if(B||K){if(n.some(U=>U.id===R)){console.log("isOverMetricSortable",R);const U=n.findIndex(V=>V.id===R);l(U);const G=n.filter(V=>V.id!==Qe.id);G.splice(U,0,Qe),h(G)}else if(M.id===fe){l(n.length);const U=[...n,Qe];h(U),d(r),c(a),x(i)}}if(C(q)){if(r.some(U=>U.id===R)){const U=r.findIndex(V=>V.id===R);l(U);const G=r.filter(V=>V.id!==We.id);G.splice(U,0,We),d(G)}else if(M.id===lt){l(r.length);const U=[...r,We];d(U),h(n),c(a),x(i)}}}else c(a),h(n),d(r),x(i)};function y(A){u(A.active.id),l(null),c(a),h(n),d(r),x(i)}function C(A){return!r.some(N=>N.name===A.column_name)}function b(A,N="SUM"){const{column_name:M,data_type:z}=A,R=[...n],q=s!==null?s:n.length,B={...A,id:de(M),name:M,label:ke(M,N),type:z,role:"metric",aggregate:N};R.splice(q,0,B),p(R)}function w(A){const N=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...i],z=s!==null?s:i.length;let R;N?R={...A,id:de(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:R={...A,id:de(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:Ne(A.column_name,"month"),granularity:"month"},M.splice(z,0,R),v(M)}function I(A){const N=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...a],z=s!==null?s:a.length;let R;N?R={...A,id:de(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:R={...A,id:de(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:Ne(A.column_name,"month"),granularity:"month"},M.splice(z,0,R),j(M)}function D(A){const N=[...r],M=s!==null?s:r.length,z={...A,id:de(A.column_name),name:A.column_name,type:A.data_type,sql:t.getDefaultFilterSql(A.data_type,k,t.fmt(A.column_name)),role:"filter"};N.splice(M,0,z),g(N)}function S(A){var R,q,B,K,J,$,U,G;const{active:N,over:M}=A,z=N.data.current;if((z==null?void 0:z.type)==="column"&&M){const V=f.find(Z=>Z.column_name===N.id);if(!V)return;const P=t.isNumberDataType(V.data_type),H=t.isTextDataType(V.data_type),Y=t.isDateDataType(V.data_type);(H||Y)&&(M.id===pe||((R=M.data.current)==null?void 0:R.type)===ze)&&I(V),(H||Y)&&(M.id===ge||((q=M.data.current)==null?void 0:q.type)===Be)?w(V):(P||H)&&(M.id===fe||((B=M.data.current)==null?void 0:B.type)===it)?(P&&b(V),H&&b(V,"COUNT")):C(V)&&(M.id===lt||((K=M.data.current)==null?void 0:K.type)===ct)&&D(V)}if(M&&((J=M.data.current)==null?void 0:J.type)===ze&&a.some(V=>V.id===N.id)){const V=a.findIndex(H=>H.id===N.id),P=a.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...a],[Y]=H.splice(V,1);H.splice(P,0,Y),j(H)}}if(M&&(($=M.data.current)==null?void 0:$.type)===Be&&i.some(V=>V.id===N.id)){const V=i.findIndex(H=>H.id===N.id),P=i.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...i],[Y]=H.splice(V,1);H.splice(P,0,Y),v(H)}}if(M&&((U=M.data.current)==null?void 0:U.type)===it&&n.some(V=>V.id===N.id)){const V=n.findIndex(H=>H.id===N.id),P=n.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...n],[Y]=H.splice(V,1);H.splice(P,0,Y),p(H)}}if(M&&((G=M.data.current)==null?void 0:G.type)===ct&&r.some(V=>V.id===N.id)){const V=r.findIndex(H=>H.id===N.id),P=r.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...r],[Y]=H.splice(V,1);H.splice(P,0,Y),g(H)}}F(A),u(null),l(null),c(a),h(n),d(r),x(i)}function F(A){const{active:N,over:M}=A,z=N.data.current;if((z==null?void 0:z.type)===St&&M){const R=o.findIndex(B=>we(B.columnId)===N.id),q=o.findIndex(B=>we(B.columnId)===M.id);if(R!==-1&&q!==-1&&R!==q){const B=[...o],[K]=B.splice(R,1);B.splice(q,0,K),m(B)}}}function O(){u(null),l(null),c(a),h(n),d(r)}return{handleDragOver:E,handleDragEnd:S,handleDragStart:y,handleDragCancel:O,sensors:T}}function de(s){return`${s}-${t.v4()}`}function ke(s,a){const n=t.toTitleCase(s.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 we(s){return`${St}-${s}`}function Ne(s,a){const n=t.toTitleCase(s.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 Un({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(N=>N.sqlGen),i=t.useEditorStore(N=>N.isDevMode),l=t.useEditorStore(N=>N.selectedConnectionId),u=t.useEditorStore(N=>{var M,z;return(z=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:z.metricColumns});t.useEditorStore(N=>{var M,z;return(z=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:z.groupByColumns});const c=t.useEditorStore(N=>N.selectedDatabaseName),h=t.useEditorStore(N=>N.selectedSchemaName),d=t.useEditorStore(N=>N.selectedTableName),x=t.useEditorStore(N=>N.selectedDatamodelId),j=t.useDashboardStore(N=>N.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=t.useDashboardActions(),{addColumnToMetricColumns:m,addColumnToGroupBy:v,setCardSql:f,setRunSql:k,setSqlGen:T,setIsShowingVisual:E}=t.useEditorActions(),{connectionType:y,modelItems:C,selectedDatamodelName:b}=t.useEditorAside();function w(N){var M;if(i){const z=t.createSqlGenConfig(N,o);T(z);const R=(M=C==null?void 0:C.find(B=>B.id===x))==null?void 0:M.name,q=t.getSql(z,t.fmt(s),t.fmt(a),R||"",y,c||"");q&&(f(q),k(!0))}if(!i){if(t.isTextDataType(N.data_type))if(u&&u.length>0){const z={...N,role:"groupby",id:de(N.column_name),name:N.column_name,type:N.data_type};v(z)}else{const z={...N,role:"metric",id:de(N.column_name),name:N.column_name,label:ke(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};m(z)}if(t.isDateDataType(N.data_type)){const z={...N,role:"groupby",id:de(N.column_name),name:N.column_name,type:N.data_type,label:Ne(N.column_name,"month"),granularity:"month"};v(z)}if(t.isNumberDataType(N.data_type)){const z={...N,role:"metric",id:de(N.column_name),name:N.column_name,label:ke(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};m(z)}}}function I(N){N===!0&&(d||b)&&l?(p({connectionId:l,connectionType:y==="S3"||y==="API"?"DuckDb":y,databaseName:c||"",schemaName:h||"",tableName:d||"",datamodelName:t.resolveDatamodelName(b),datamodelId:x||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:l||"",connectionType:y||"",tableName:d||"",datamodelName:t.resolveDatamodelName(b),datamodelId:x||"",databaseName:c||"",schemaName:h||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function D(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:b,connectionType:y,databaseName:c||""});E(!1);const M=y==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;f(M),k(!0)}function S(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:b,connectionType:y,databaseName:c||""});f(`SELECT COUNT(*) as count FROM ${N}`),k(!0)}function F(){return(j==null?void 0:j.find(N=>N.connectionId===l&&(N.tableName===d||N.datamodelName===b)))!==void 0}function O(N){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(N),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Nt,{column:N}),e.jsx("span",{children:N.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(N.data_type)&&e.jsx(Gn,{column:N})})]}):e.jsx(Hn,{onClick:w,column:N})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${F()?"Remove from":"Add to"} Assistant Scope`,pressed:F(),onPressedChange:I,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":F(),"text-muted-foreground":!F()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:D,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(vn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Qt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((N,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:A()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(N=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:O(N)},N.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function rs({ColumnsComponent:s,type:a}){var Lt;const n=t.useEditorStore(X=>X.card),r=t.useEditorStore(X=>X.selectedConnectionId),o=t.useDashboardStore(X=>X.showFilters),i=t.useEditorStore(X=>X.selectedDatamodelId),l=t.useEditorStore(X=>X.selectedDatabaseName),u=t.useEditorStore(X=>X.selectedSchemaName),c=t.useEditorStore(X=>X.selectedTableName),h=t.useEditorStore(X=>X.isDevMode),{setSelectedTableName:d,setIsDevMode:x,setCardSql:j}=t.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:m,databaseItems:v,tableItems:f,columns:k,isConnectionsLoading:T,isModelsLoading:E,isConnectionsError:y,isModelsError:C,isDatabasesLoadingOrFetching:b,isDatabaseError:w,isSchemaLoadingOrFetching:I,isSchemaError:D,isColumnsError:S,isColumnsLoadingOrFetching:F,isTableLoadingOrFetching:O,isTableError:A,connectionType:N,isNonDbConnection:M,refetchDatabases:z,refetchModels:R,refetchSchemas:q,refetchTables:B,refetchColumns:K,refetchConnections:J,handleConnectionChange:$,handleDatabaseChange:U,handleSchemaChange:G,handleDatamodelChange:V,handleTableChange:P,tableName:H,schemaName:Y}=t.useEditorAside(),{data:Z,refetch:_}=t.useDashboardCardQuery(n);function Q(){return s?s(Y,H,k):e.jsx(Un,{schemaName:Y,tableName:H,columns:k,status:F?"Loading...":S?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ue(X){X===!0?Z&&(j(Z.userSql),setTimeout(()=>{_()},100)):j(""),x(X)}function Me(){if(!r||N==="S3"||N==="API")return null;if(!i||i==="none")return e.jsx(be,{refetch:z,showNone:!0,onChange:U,isError:w,isLoading:b,items:v,value:l||"",title:"Database",type:"combobox"})}function Ds(){if(r&&!M&&(!l||l==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Ts(){if(!r||N==="S3"||N==="API")return null;if(!l||l==="none")return e.jsx(be,{refetch:R,showNone:!0,onChange:V,isError:C,isLoading:E,items:g,value:i||"",title:"Model",type:"combobox"})}function Ms(){return!r||N==="S3"||N==="API"||!l||l==="none"?null:e.jsx(be,{refetch:q,onChange:G,isError:D,isLoading:I,items:m,value:u||"",title:"Schema",type:"combobox"})}function As(){function X(){let he=!1;return N==="API"?(he=!1,he):((N==="S3"||r&&l&&l!=="none"&&u)&&(he=!0),he)}return X()?e.jsx(be,{refetch:B,onChange:P,isError:A,items:f,isLoading:O,value:c||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.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(be,{refetch:J,items:p,title:"Connection",value:r||"",onChange:$,isLoading:T,isError:y,type:"combobox",connectionTooltip:((Lt=p==null?void 0:p.find(X=>X.id===r))==null?void 0:Lt.type)||""}),Me(),Ds(),Ts(),Ms(),As()]}),Q(),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(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:ue,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Sn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function os({sql:s,error:a,onClick:n}){const r=t.useEditorStore(c=>c.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:l}=t.useEditorActions();function u(){o(!r),i(s),setTimeout(()=>{l(!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(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&a,s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&e.jsxs(t.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(pn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function is({sql:s,error:a,onClick:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Ut,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-full min-w-fit max-w-[700px]",children:e.jsx(os,{sql:s,error:a,onClick:n})})]})}var ls={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Vt=L.createContext&&L.createContext(ls),Yn=["attr","size","title"];function Kn(s,a){if(s==null)return{};var n=Qn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Qn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Re(){return Re=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Re.apply(this,arguments)}function qt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Pe(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?qt(Object(n),!0).forEach(function(r){Wn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):qt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Wn(s,a,n){return a=Xn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function Xn(s){var a=Zn(s,"string");return typeof a=="symbol"?a:a+""}function Zn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function cs(s){return s&&s.map((a,n)=>L.createElement(a.tag,Pe({key:n},a.attr),cs(a.child)))}function je(s){return a=>L.createElement(ea,Re({attr:Pe({},s.attr)},a),cs(s.child))}function ea(s){var a=n=>{var{attr:r,size:o,title:i}=s,l=Kn(s,Yn),u=o||n.size||"1em",c;return n.className&&(c=n.className),s.className&&(c=(c?c+" ":"")+s.className),L.createElement("svg",Re({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,l,{className:c,style:Pe(Pe({color:s.color||n.color},n.style),s.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Vt!==void 0?L.createElement(Vt.Consumer,null,n=>a(n)):a(ls)}function ta(s){return je({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:[]}]})(s)}function ds(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(m=>m.theme),r=t.useEditorStore(m=>m.frame),o=t.useEditorStore(m=>m.card),i=t.useEditorStore(m=>m.activeTabCardId),l=t.Le(),{refetch:u}=t.useDashboardCardQuery(o),{updateCardTab:c,setRunSql:h}=t.useEditorActions(),d=L.useRef(),x=L.useRef({}),j=r.cards.find(m=>m.id===i),p=L.useCallback(()=>{let m="";return s==="python"&&(m=(j==null?void 0:j.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(m=(j==null?void 0:j.sql)||""),m},[s,j]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(d.current&&l){const m=d.current.getModel();m&&(x.current[o.id]=m);let v=x.current[i];if(!v){const f=p();v=l.editor.createModel(f,s),x.current[i]=v}d.current.setModel(v)}c(i,o),h(!0)}},[i,o,c,l,h,s,p]),L.useEffect(()=>{if(!l)return;const m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?m:n;l.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[a,n,l]),L.useEffect(()=>{const m=d.current;m&&l&&o&&m.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return u(),!1})},[l,u,o]);function g(m,v){if(d.current=m,!x.current[o.id]){const f=m.getModel(),k=p();x.current[o.id]=f||(v==null?void 0:v.editor.createModel(k,s))||m.getModel()}m.setModel(x.current[o.id])}return{handleEditorDidMount:g}}function sa(){const s=t.useEditorStore(l=>l.card.sql),a=t.useEditorStore(l=>l.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=ds("sql");function i(l){n(l),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&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(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function na(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=ds("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function aa({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ra(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(B=>B.frame);const i=t.useEditorStore(B=>B.card);t.useEditorStore(B=>B.isShowingVisual),t.useEditorStore(B=>B.selectedConnectionId),t.useEditorStore(B=>B.tempQueryData),t.useEditorStore(B=>B.selectedDatabaseName),t.useEditorStore(B=>B.selectedDatamodelId),t.useEditorStore(B=>B.selectedSchemaName);const l=t.useEditorStore(B=>B.showAIDialog);t.useEditorStore(B=>B.selectedTableName);const u=t.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),c=t.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{sheetFilterValues:h}=t.useSheetFilterValues(),{setCardCustomCfg:d,setQueryResultColumns:x,setCardSql:j,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:m,setCardType:v,setCardPython:f,runAssistant:k,setShowAIDialog:T}=t.useEditorActions();t.useEditorStore(B=>B.onSave),t.useEditorStore(B=>B.onClose),t.useEditorStore(B=>B.actions.setSqlGen);const E=t.useEditorStore(B=>B.runSql),y=t.useEditorStore(B=>B.actions.setRunSql),C=t.useEditorStore(B=>B.actions.setIsSqlRunning),{data:b,isLoading:w,isFetching:I,isSuccess:D,isError:S,error:F,queryKey:O,refetch:A,errorMessage:N}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(b&&(b.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:B}=t.getKeys(b.records);x(B)}},[b,x,g]),L.useEffect(()=>{(w||I)&&C(!0),(S||D)&&C(!1),S&&(x([]),g(""))},[w,I,b,g,S,D,C,x,F]),L.useEffect(()=>{E&&(s.getQueryData(O)||A(),y(!1))},[E,A,y,O,s]);async function M(){const B=`Can you help me debug this query in the current table scope?
391
+ */const Zt=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function Ct(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(l=>es(l))}})}})}}function es(s){return{...s,customCfg:On(s.customCfg),data:[]}}function On(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Fn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function ot(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:l}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:l,operation:"update"})}async function zn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Bn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(m=>m.lenses),{setLenses:i,setSelectedLensId:l}=t.useDashboardActions(),[u,c]=L.useState(!1),[h,d]=L.useState(!1),x=t.useDashboardStore(m=>m.dashboard),g=t.useDashboardStore(m=>m.filterValues),{authToken:p}=t.useSemaphorContext();async function j(){c(!0);const m=Ct(x),v=await Fn(s,m,g,p==null?void 0:p.accessToken);v&&(i([...o||[],v]),l(v.id),d(!1)),c(!1)}return e.jsxs(t.Dialog,{open:h,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.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(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:m=>{a(m.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(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:u,children:u?"Creating...":"Add"})})]})]})}function Rn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(d=>d.lenses),r=t.useDashboardStore(d=>d.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:l}=t.useSemaphorContext();async function u(d){i(d)}async function c(d){if(await zn(d,l==null?void 0:l.accessToken)){const g=n==null?void 0:n.filter(p=>p.id!==d);o(g||[]),i("original")}}async function h(d){const x=n==null?void 0:n.map(j=>j.id===d.id?{...j,isDefault:!d.isDefault}:{...j,isDefault:!1});o(x||[]);const g={...d,isDefault:!d.isDefault};await ot(g,l==null?void 0:l.accessToken);const p=n==null?void 0:n.find(j=>j.isDefault);if(p&&p.id!==d.id){const j={...p,isDefault:!1};await ot(j,l==null?void 0:l.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(hn,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:u,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(d=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:d.id,children:[e.jsx("p",{children:d.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(fn,{onClick:x=>{x.preventDefault(),h(d)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!d.isDefault,"text-green-500":d.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:x=>{x.preventDefault(),c(d.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},d.id))]})]})]})}function ts(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function ss(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=ts();if(s)return;const l=new URLSearchParams;l.set("token",(a==null?void 0:a.accessToken)||""),l.set("theme",n),l.set("filterValues",JSON.stringify(r)),l.set("selectedSheetId",i||"");const u=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(l.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const d=(await(await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,x=document.createElement("a");x.href=d;const g=`${o}-${new Date().toISOString()}.pdf`;x.download=g,x.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function Pn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await ss()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(ce,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function le({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:l,showPlaceholderLabel:u=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),u&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))]})})]})}const Rt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function ns({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:l}=Vn(),[u,c]=L.useState(""),[h,d]=L.useState(Rt[0].value),[x,g]=L.useState("06:00"),[p,j]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(tn,{className:"size-4"})})}),e.jsx(t.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(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:u,onChange:m=>c(m.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:m=>{j(m.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(le,{className:"col-span-2 h-8",label:"Select Frequency",options:Rt,value:h,onValueChange:m=>d(m)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:x,onChange:m=>g(m.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:u,frequency:h,time:x,subject:p}),g("00:00"),c(""),j("")},className:"h-8 p-2",disabled:o==="loading"||!u,children:[o==="loading"&&e.jsx(ce,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Ut,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.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"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(m=>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:[t.titleCase(m.frequency)," "]}),e.jsx(t.Label,{children:m.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Pt,{tooltip:`Next Run: ${new Date(m.nextRun).toLocaleString()} ${m.timezone}`,children:e.jsx(en,{className:"size-3.5"})}),e.jsx(Pt,{tooltip:`${m.endUserEmail}`,children:e.jsx(Cn,{className:"size-3.5"})}),l===m.id?e.jsx(ce,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(m.id),className:"size-3.5 cursor-pointer"})]})]},m.id))})]})]})]})})]})})}const Pt=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function Vn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),l=t.useDashboardStore(T=>T.authToken),u=t.useDashboardStore(T=>T.dashboard.id),c=t.useDashboardStore(T=>T.dashboard.title),{endUserId:h}=t.getTenantAndEndUserId((l==null?void 0:l.accessToken)||""),d="https://semaphor.cloud/api/v1/subscriptions/get",x={dashboardId:u,endUserId:h},{data:g,isLoading:p,isError:j,isFetching:m,refetch:v}=t.useQuery({queryKey:["subscriptions",u,h],queryFn:()=>t.getRequest(d,(l==null?void 0:l.accessToken)||"",x),enabled:!!(l!=null&&l.accessToken)&&!!u&&!!h});async function f({email:T,subject:E,frequency:y,time:C}){const{authToken:b,...w}=ts(),I=Intl.DateTimeFormat().resolvedOptions().timeZone,D={email:T,frequency:y,time:C,timezone:I,endUserId:h,endUserEmail:T,subject:E||c||"Scheduled Dashboard",dashboardId:u,dashboardParams:w};a("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const F=await t.postRequestRegular(S,(b==null?void 0:b.accessToken)||"",{...D});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(F){console.error(F),a("error"),r(F.message)}}async function k(T){const E="https://semaphor.cloud/api/v1/subscriptions/delete";i(T);try{await t.postRequestRegular(E,(l==null?void 0:l.accessToken)||"",{id:T}),v(),setTimeout(()=>{i(null)},2e3)}catch(y){console.error(y),i(null),a("error"),r(y.message)}}return{data:g,isLoading:p,isFetching:m,isError:j,isDeleting:o,refetch:v,handleScheduleSubscription:f,handleDeleteSubscription:k,status:s,error:n}}function qn(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(D=>D.theme);const a=t.useDashboardStore(D=>D.lenses),n=t.useDashboardStore(D=>D.selectedLensId),r=a==null?void 0:a.find(D=>D.id===n),o=t.useDashboardStore(D=>D.dashboard);t.useDashboardStore(D=>D.selectedSheetId);const i=t.useDashboardStore(D=>D.isDashboardEditing),l=t.useEditorStore(D=>D.selectedConnectionId),[u,c]=L.useState(!1),h=t.useDashboardStore(D=>D.filterValues),d=t.useDashboardStore(D=>D.isVisualEditing),x=t.useDashboardStore(D=>D.showFilters);t.useDashboardStore(D=>D.showDashboardJSON);const g=t.useDashboardStore(D=>D.onSaveFunction),p=t.useDashboardStore(D=>D.actions.setShowFilters),{addFrame:j,setSelectedFrameId:m}=t.useDashboardStore(D=>D.actions),{getSelectedSheet:v,setIsDashboardEditing:f,setShowDashboardJSON:k}=t.useDashboardStore(D=>D.actions),T=v(),{tenantId:E,endUserId:y}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),C=L.useMemo(()=>E||y,[E,y]),b=()=>{if(!i||!T)return;const D={connectionId:l,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},S={id:t.v4(),cards:[D],activeCardId:D.id};j(T.id,S),m(S.id)},w=()=>{f(!0)};async function I(){if(c(!0),!n||!r)return;const D=Ct(o),S=JSON.stringify(D),F={...r,template:S,filterValues:h};await ot(F,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),g==null||g(D),c(!1)}return d?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!d&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!d&&e.jsx(Pn,{}),!d&&e.jsx(ns,{}),i&&!d&&C&&e.jsx(Bn,{}),!d&&C&&e.jsx(Rn,{}),i&&!d&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:b,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!d&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{f(!1),k(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!d&&C&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:I,size:"sm",children:e.jsx(Tn,{className:"h-4 w-4"})}),!x&&!d&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>p(!0),size:"sm",children:e.jsx(ft,{className:"h-4 w-4"})}),!d&&i&&!1,!d&&!1]})]})}function _n({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:l,className:u,icon:c,showNone:h=!1}){const d=re.useRef(null),[x,g]=re.useState(!1),[p,j]=re.useState("100%"),m=h?[...a||[],{id:"none",name:"None"}]:a;re.useLayoutEffect(()=>{d.current&&j(d.current.offsetWidth)},[]);function v(){var k;return o?"Loading...":i?"Error":n?(k=a==null?void 0:a.find(T=>T.id===n))==null?void 0:k.name:`Select ${s}`}function f(k,T){r(T),g(!1)}return e.jsxs(t.Popover,{open:x,onOpenChange:g,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:d,variant:"outline",role:"combobox","aria-expanded":x,className:t.cn("flex h-9 w-full justify-between",u),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("div",{className:"mr-2",children:c}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:p},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:l,children:e.jsx(Kt,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:m==null?void 0:m.map(k=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:k.name,onSelect:T=>f(T,k.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===k.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:k.name,children:k.name})]})},k.id))})]})]})})]})}function ve({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:l,showNone:u=!1,className:c,disabled:h=!1,type:d="combobox"}){const x=r?"Loading...":o?"Error":n;function g(){if(s==="Connection")return e.jsx(In,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(kn,{className:"size-4"});if(s==="Table")return e.jsx(He,{className:"size-4"});if(s==="Model")return e.jsx(Ks,{className:"size-4"})}function p(){return e.jsxs(t.Select,{disabled:h,value:x,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",c),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(Kt,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[u&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((m,v)=>e.jsx(t.SelectItem,{value:m.id,children:m.name},v))]}),(r||o)&&e.jsx(t.SelectItem,{value:x,children:x})]})})]})}function j(){return e.jsx(_n,{icon:g(),items:a,value:x,onChange:l||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:u})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:d==="select"?p():j()})})}function Gn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(m=>m.selectedTableName),o=t.useEditorStore(m=>m.selectedSchemaName),i=t.useEditorStore(m=>m.selectedDatabaseName),l=t.useEditorStore(m=>m.selectedDatamodelId),u=t.useEditorStore(m=>m.sqlGen),{modelItems:c,connectionType:h}=t.useEditorAside(),d=t.useEditorStore(m=>m.actions.setSqlGen),x=t.useEditorStore(m=>m.actions.setCardSql),g=t.useEditorStore(m=>m.actions.setRunSql);function p(m,v){var E;const f=t.createSqlGenConfig(m,u,v),k=(E=c==null?void 0:c.find(y=>y.id===l))==null?void 0:E.name;d(f);const T=t.getSql(f,t.fmt(o||""),t.fmt(r),k||"",h,i||"");T&&(x(T),g(!0)),n(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function Nt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(gt,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Xt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Qs,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Ue({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Nt,{column:s}),e.jsx("span",{children:s.column_name})]})}function $n({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:l}=t.useDraggable({id:s,data:{type:n}}),u=l?{translate:t.CSS.Translate.toString(l),transform:t.CSS.Transform.toString(l)}:void 0;return e.jsx("div",{ref:i,style:u,...o,...r,children:a})}function Hn({onClick:s,column:a}){const n=t.useDndStore(d=>d.activeId),r=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.groupByColumns}),o=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.metricColumns}),i=t.useEditorStore(d=>{var x;return(x=d.card.queryConfig)==null?void 0:x.filterColumns});function l(d){return u(d)||c(d)||h(d)}function u(d){return r==null?void 0:r.some(x=>x.name===d.column_name)}function c(d){return o==null?void 0:o.some(x=>x.name===d.column_name)}function h(d){return i==null?void 0:i.some(x=>x.name===d.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":l(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Ue,{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(Ue,{column:a})}),e.jsx($n,{id:a.column_name,type:"column",children:e.jsx(Ue,{column:a})})]})}const Ye={id:"__placeholder__",role:"groupby",type:"string"},Ke={id:"__placeholder__",role:"groupby",type:"string"},Qe={id:"__placeholder__",role:"metric",type:"number"},We={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},as={id:"__placeholder__"},fe="droppable-group-by",ge="droppable-metrics",je="droppable-pivot-by",ze="sortable-group-by",it="sortable-metrics",Be="sortable-pivot-by",lt="droppable-filters",ct="sortable-filters",St="sortable-order-by";function Jn(){const s=t.useDndStore(A=>A.insertIndex),a=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.groupByColumns)||[]}),n=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.metricColumns)||[]}),r=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.filterColumns)||[]}),o=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.orderBy)||[]}),i=t.useEditorStore(A=>{var N;return((N=A.card.queryConfig)==null?void 0:N.pivotColumns)||[]}),{setInsertIndex:l,setActiveId:u,setPreviewGroupByColumns:c,setPreviewMetricColumns:h,setPreviewFilterColumns:d,setPreviewPivotColumns:x}=t.useDndActions(),{setGroupByColumns:g,setMetricColumns:p,setFilterColumns:j,setOrderByColumns:m,setPivotByColumns:v}=t.useEditorActions(),{columns:f}=t.useDataColumns(),{formattedTableName:k}=t.useEditorAside(),T=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),E=A=>{var z;const{active:N,over:M}=A;if(((z=N.data.current)==null?void 0:z.type)==="column"&&M){const R=M.id,q=f.find($=>$.column_name===N.id);if(!q)return;const B=t.isNumberDataType(q.data_type),K=t.isTextDataType(q.data_type),J=t.isDateDataType(q.data_type);if(K||J){if(a.some(Y=>Y.id===R)){const Y=a.findIndex(V=>V.id===R);l(Y);const _=a.filter(V=>V.id!==Ye.id);_.splice(Y,0,Ye),c(_)}else if(M.id===fe){l(a.length);const Y=[...a,Ye];c(Y),h(n),d(r)}}if(K||J){if(i.some(Y=>Y.id===R)){const Y=i.findIndex(V=>V.id===R);l(Y);const _=i.filter(V=>V.id!==Ke.id);_.splice(Y,0,Ke),x(_)}else if(M.id===je){l(i.length);const Y=[...i,Ke];x(Y),c(a),h(n),d(r)}}if(B||K){if(n.some(Y=>Y.id===R)){console.log("isOverMetricSortable",R);const Y=n.findIndex(V=>V.id===R);l(Y);const _=n.filter(V=>V.id!==Qe.id);_.splice(Y,0,Qe),h(_)}else if(M.id===ge){l(n.length);const Y=[...n,Qe];h(Y),d(r),c(a),x(i)}}if(C(q)){if(r.some(Y=>Y.id===R)){const Y=r.findIndex(V=>V.id===R);l(Y);const _=r.filter(V=>V.id!==We.id);_.splice(Y,0,We),d(_)}else if(M.id===lt){l(r.length);const Y=[...r,We];d(Y),h(n),c(a),x(i)}}}else c(a),h(n),d(r),x(i)};function y(A){u(A.active.id),l(null),c(a),h(n),d(r),x(i)}function C(A){return!r.some(N=>N.name===A.column_name)}function b(A,N="SUM"){const{column_name:M,data_type:z}=A,R=[...n],q=s!==null?s:n.length,B={...A,id:ue(M),name:M,label:Ee(M,N),type:z,role:"metric",aggregate:N};R.splice(q,0,B),p(R)}function w(A){const N=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...i],z=s!==null?s:i.length;let R;N?R={...A,id:ue(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:R={...A,id:ue(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:Se(A.column_name,"month"),granularity:"month"},M.splice(z,0,R),v(M)}function I(A){const N=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...a],z=s!==null?s:a.length;let R;N?R={...A,id:ue(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:R={...A,id:ue(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:Se(A.column_name,"month"),granularity:"month"},M.splice(z,0,R),g(M)}function D(A){const N=[...r],M=s!==null?s:r.length,z={...A,id:ue(A.column_name),name:A.column_name,type:A.data_type,sql:t.getDefaultFilterSql(A.data_type,k,t.fmt(A.column_name)),role:"filter"};N.splice(M,0,z),j(N)}function S(A){var R,q,B,K,J,$,Y,_;const{active:N,over:M}=A,z=N.data.current;if((z==null?void 0:z.type)==="column"&&M){const V=f.find(Z=>Z.column_name===N.id);if(!V)return;const P=t.isNumberDataType(V.data_type),H=t.isTextDataType(V.data_type),U=t.isDateDataType(V.data_type);(H||U)&&(M.id===fe||((R=M.data.current)==null?void 0:R.type)===ze)&&I(V),(H||U)&&(M.id===je||((q=M.data.current)==null?void 0:q.type)===Be)?w(V):(P||H)&&(M.id===ge||((B=M.data.current)==null?void 0:B.type)===it)?(P&&b(V),H&&b(V,"COUNT")):C(V)&&(M.id===lt||((K=M.data.current)==null?void 0:K.type)===ct)&&D(V)}if(M&&((J=M.data.current)==null?void 0:J.type)===ze&&a.some(V=>V.id===N.id)){const V=a.findIndex(H=>H.id===N.id),P=a.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...a],[U]=H.splice(V,1);H.splice(P,0,U),g(H)}}if(M&&(($=M.data.current)==null?void 0:$.type)===Be&&i.some(V=>V.id===N.id)){const V=i.findIndex(H=>H.id===N.id),P=i.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...i],[U]=H.splice(V,1);H.splice(P,0,U),v(H)}}if(M&&((Y=M.data.current)==null?void 0:Y.type)===it&&n.some(V=>V.id===N.id)){const V=n.findIndex(H=>H.id===N.id),P=n.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...n],[U]=H.splice(V,1);H.splice(P,0,U),p(H)}}if(M&&((_=M.data.current)==null?void 0:_.type)===ct&&r.some(V=>V.id===N.id)){const V=r.findIndex(H=>H.id===N.id),P=r.findIndex(H=>H.id===M.id);if(V!==-1&&P!==-1&&V!==P){const H=[...r],[U]=H.splice(V,1);H.splice(P,0,U),j(H)}}F(A),u(null),l(null),c(a),h(n),d(r),x(i)}function F(A){const{active:N,over:M}=A,z=N.data.current;if((z==null?void 0:z.type)===St&&M){const R=o.findIndex(B=>ke(B.columnId)===N.id),q=o.findIndex(B=>ke(B.columnId)===M.id);if(R!==-1&&q!==-1&&R!==q){const B=[...o],[K]=B.splice(R,1);B.splice(q,0,K),m(B)}}}function O(){u(null),l(null),c(a),h(n),d(r)}return{handleDragOver:E,handleDragEnd:S,handleDragStart:y,handleDragCancel:O,sensors:T}}function ue(s){return`${s}-${t.v4()}`}function Ee(s,a){const n=t.toTitleCase(s.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 ke(s){return`${St}-${s}`}function Se(s,a){const n=t.toTitleCase(s.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 Un({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(N=>N.sqlGen),i=t.useEditorStore(N=>N.isDevMode),l=t.useEditorStore(N=>N.selectedConnectionId),u=t.useEditorStore(N=>{var M,z;return(z=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:z.metricColumns});t.useEditorStore(N=>{var M,z;return(z=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:z.groupByColumns});const c=t.useEditorStore(N=>N.selectedDatabaseName),h=t.useEditorStore(N=>N.selectedSchemaName),d=t.useEditorStore(N=>N.selectedTableName),x=t.useEditorStore(N=>N.selectedDatamodelId),g=t.useDashboardStore(N=>N.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:j}=t.useDashboardActions(),{addColumnToMetricColumns:m,addColumnToGroupBy:v,setCardSql:f,setRunSql:k,setSqlGen:T,setIsShowingVisual:E}=t.useEditorActions(),{connectionType:y,modelItems:C,selectedDatamodelName:b}=t.useEditorAside();function w(N){var M;if(i){const z=t.createSqlGenConfig(N,o);T(z);const R=(M=C==null?void 0:C.find(B=>B.id===x))==null?void 0:M.name,q=t.getSql(z,t.fmt(s),t.fmt(a),R||"",y,c||"");q&&(f(q),k(!0))}if(!i){if(t.isTextDataType(N.data_type))if(u&&u.length>0){const z={...N,role:"groupby",id:ue(N.column_name),name:N.column_name,type:N.data_type};v(z)}else{const z={...N,role:"metric",id:ue(N.column_name),name:N.column_name,label:Ee(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};m(z)}if(t.isDateDataType(N.data_type)){const z={...N,role:"groupby",id:ue(N.column_name),name:N.column_name,type:N.data_type,label:Se(N.column_name,"month"),granularity:"month"};v(z)}if(t.isNumberDataType(N.data_type)){const z={...N,role:"metric",id:ue(N.column_name),name:N.column_name,label:Ee(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};m(z)}}}function I(N){N===!0&&(d||b)&&l?(p({connectionId:l,connectionType:y==="S3"||y==="API"?"DuckDb":y,databaseName:c||"",schemaName:h||"",tableName:d||"",datamodelName:t.resolveDatamodelName(b),datamodelId:x||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(j({connectionId:l||"",connectionType:y||"",tableName:d||"",datamodelName:t.resolveDatamodelName(b),datamodelId:x||"",databaseName:c||"",schemaName:h||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function D(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:b,connectionType:y,databaseName:c||""});E(!1);const M=y==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;f(M),k(!0)}function S(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:b,connectionType:y,databaseName:c||""});f(`SELECT COUNT(*) as count FROM ${N}`),k(!0)}function F(){return(g==null?void 0:g.find(N=>N.connectionId===l&&(N.tableName===d||N.datamodelName===b)))!==void 0}function O(N){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(N),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Nt,{column:N}),e.jsx("span",{children:N.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(N.data_type)&&e.jsx(Gn,{column:N})})]}):e.jsx(Hn,{onClick:w,column:N})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${F()?"Remove from":"Add to"} Assistant Scope`,pressed:F(),onPressedChange:I,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":F(),"text-muted-foreground":!F()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:D,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(vn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Qt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((N,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:A()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(N=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:O(N)},N.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function rs({ColumnsComponent:s,type:a}){var Lt;const n=t.useEditorStore(X=>X.card),r=t.useEditorStore(X=>X.selectedConnectionId),o=t.useDashboardStore(X=>X.showFilters),i=t.useEditorStore(X=>X.selectedDatamodelId),l=t.useEditorStore(X=>X.selectedDatabaseName),u=t.useEditorStore(X=>X.selectedSchemaName),c=t.useEditorStore(X=>X.selectedTableName),h=t.useEditorStore(X=>X.isDevMode),{setSelectedTableName:d,setIsDevMode:x,setCardSql:g}=t.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:m,databaseItems:v,tableItems:f,columns:k,isConnectionsLoading:T,isModelsLoading:E,isConnectionsError:y,isModelsError:C,isDatabasesLoadingOrFetching:b,isDatabaseError:w,isSchemaLoadingOrFetching:I,isSchemaError:D,isColumnsError:S,isColumnsLoadingOrFetching:F,isTableLoadingOrFetching:O,isTableError:A,connectionType:N,isNonDbConnection:M,refetchDatabases:z,refetchModels:R,refetchSchemas:q,refetchTables:B,refetchColumns:K,refetchConnections:J,handleConnectionChange:$,handleDatabaseChange:Y,handleSchemaChange:_,handleDatamodelChange:V,handleTableChange:P,tableName:H,schemaName:U}=t.useEditorAside(),{data:Z,refetch:de}=t.useDashboardCardQuery(n);function G(){return s?s(U,H,k):e.jsx(Un,{schemaName:U,tableName:H,columns:k,status:F?"Loading...":S?"Error":"Success"})}function Q(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function se(X){X===!0?Z&&(g(Z.userSql),setTimeout(()=>{de()},100)):g(""),x(X)}function me(){if(!r||N==="S3"||N==="API")return null;if(!i||i==="none")return e.jsx(ve,{refetch:z,showNone:!0,onChange:Y,isError:w,isLoading:b,items:v,value:l||"",title:"Database",type:"combobox"})}function Ds(){if(r&&!M&&(!l||l==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Ts(){if(!r||N==="S3"||N==="API")return null;if(!l||l==="none")return e.jsx(ve,{refetch:R,showNone:!0,onChange:V,isError:C,isLoading:E,items:j,value:i||"",title:"Model",type:"combobox"})}function Ms(){return!r||N==="S3"||N==="API"||!l||l==="none"?null:e.jsx(ve,{refetch:q,onChange:_,isError:D,isLoading:I,items:m,value:u||"",title:"Schema",type:"combobox"})}function As(){function X(){let xe=!1;return N==="API"?(xe=!1,xe):((N==="S3"||r&&l&&l!=="none"&&u)&&(xe=!0),xe)}return X()?e.jsx(ve,{refetch:B,onChange:P,isError:A,items:f,isLoading:O,value:c||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.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(ve,{refetch:J,items:p,title:"Connection",value:r||"",onChange:$,isLoading:T,isError:y,type:"combobox",connectionTooltip:((Lt=p==null?void 0:p.find(X=>X.id===r))==null?void 0:Lt.type)||""}),me(),Ds(),Ts(),Ms(),As()]}),G(),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(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:se,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:Q,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Sn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function os({sql:s,error:a,onClick:n}){const r=t.useEditorStore(c=>c.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:l}=t.useEditorActions();function u(){o(!r),i(s),setTimeout(()=>{l(!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(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&a,s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&e.jsxs(t.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(pn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function is({sql:s,error:a,onClick:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Ut,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-full min-w-fit max-w-[700px]",children:e.jsx(os,{sql:s,error:a,onClick:n})})]})}var ls={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Vt=L.createContext&&L.createContext(ls),Yn=["attr","size","title"];function Kn(s,a){if(s==null)return{};var n=Qn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Qn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Re(){return Re=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Re.apply(this,arguments)}function qt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Pe(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?qt(Object(n),!0).forEach(function(r){Wn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):qt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Wn(s,a,n){return a=Xn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function Xn(s){var a=Zn(s,"string");return typeof a=="symbol"?a:a+""}function Zn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function cs(s){return s&&s.map((a,n)=>L.createElement(a.tag,Pe({key:n},a.attr),cs(a.child)))}function ye(s){return a=>L.createElement(ea,Re({attr:Pe({},s.attr)},a),cs(s.child))}function ea(s){var a=n=>{var{attr:r,size:o,title:i}=s,l=Kn(s,Yn),u=o||n.size||"1em",c;return n.className&&(c=n.className),s.className&&(c=(c?c+" ":"")+s.className),L.createElement("svg",Re({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,l,{className:c,style:Pe(Pe({color:s.color||n.color},n.style),s.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Vt!==void 0?L.createElement(Vt.Consumer,null,n=>a(n)):a(ls)}function ta(s){return ye({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:[]}]})(s)}function ds(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(m=>m.theme),r=t.useEditorStore(m=>m.frame),o=t.useEditorStore(m=>m.card),i=t.useEditorStore(m=>m.activeTabCardId),l=t.Le(),{refetch:u}=t.useDashboardCardQuery(o),{updateCardTab:c,setRunSql:h}=t.useEditorActions(),d=L.useRef(),x=L.useRef({}),g=r.cards.find(m=>m.id===i),p=L.useCallback(()=>{let m="";return s==="python"&&(m=(g==null?void 0:g.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(m=(g==null?void 0:g.sql)||""),m},[s,g]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(d.current&&l){const m=d.current.getModel();m&&(x.current[o.id]=m);let v=x.current[i];if(!v){const f=p();v=l.editor.createModel(f,s),x.current[i]=v}d.current.setModel(v)}c(i,o),h(!0)}},[i,o,c,l,h,s,p]),L.useEffect(()=>{if(!l)return;const m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?m:n;l.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[a,n,l]),L.useEffect(()=>{const m=d.current;m&&l&&o&&m.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return u(),!1})},[l,u,o]);function j(m,v){if(d.current=m,!x.current[o.id]){const f=m.getModel(),k=p();x.current[o.id]=f||(v==null?void 0:v.editor.createModel(k,s))||m.getModel()}m.setModel(x.current[o.id])}return{handleEditorDidMount:j}}function sa(){const s=t.useEditorStore(l=>l.card.sql),a=t.useEditorStore(l=>l.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=ds("sql");function i(l){n(l),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&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(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function na(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=ds("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function aa({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ra(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(B=>B.frame);const i=t.useEditorStore(B=>B.card);t.useEditorStore(B=>B.isShowingVisual),t.useEditorStore(B=>B.selectedConnectionId),t.useEditorStore(B=>B.tempQueryData),t.useEditorStore(B=>B.selectedDatabaseName),t.useEditorStore(B=>B.selectedDatamodelId),t.useEditorStore(B=>B.selectedSchemaName);const l=t.useEditorStore(B=>B.showAIDialog);t.useEditorStore(B=>B.selectedTableName);const u=t.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),c=t.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{sheetFilterValues:h}=t.useSheetFilterValues(),{setCardCustomCfg:d,setQueryResultColumns:x,setCardSql:g,setTempQueryData:p,setPythonStdOut:j,setCardPreferences:m,setCardType:v,setCardPython:f,runAssistant:k,setShowAIDialog:T}=t.useEditorActions();t.useEditorStore(B=>B.onSave),t.useEditorStore(B=>B.onClose),t.useEditorStore(B=>B.actions.setSqlGen);const E=t.useEditorStore(B=>B.runSql),y=t.useEditorStore(B=>B.actions.setRunSql),C=t.useEditorStore(B=>B.actions.setIsSqlRunning),{data:b,isLoading:w,isFetching:I,isSuccess:D,isError:S,error:F,queryKey:O,refetch:A,errorMessage:N}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(b&&(b.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:B}=t.getKeys(b.records);x(B)}},[b,x,j]),L.useEffect(()=>{(w||I)&&C(!0),(S||D)&&C(!1),S&&(x([]),j(""))},[w,I,b,j,S,D,C,x,F]),L.useEffect(()=>{E&&(s.getQueryData(O)||A(),y(!1))},[E,A,y,O,s]);async function M(){const B=`Can you help me debug this query in the current table scope?
392
392
 
393
393
  Error:
394
394
 
@@ -400,11 +400,11 @@
400
400
 
401
401
  ${c?`Python:
402
402
  ${c}`:""}
403
- `;k(B)}function z(){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(aa,{jsonString:JSON.stringify(h,null,2)})})}),h&&h.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(ft,{className:"size-3.5 text-muted-foreground"})})]})}function R(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.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(sa,{})}),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(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.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(na,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){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(t.Button,{title:"Shift + Enter",disabled:w||I,onClick:()=>{A()},className:"h-8 shrink-0",size:"sm",children:[w||I?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(is,{sql:b==null?void 0:b.sql,error:N,onClick:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:B=>n(B),className:"",size:"sm",children:e.jsx(ta,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:l,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:l?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}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:[R(),z()]}),q()]})}function oa({data:s}){var l;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(u=>({accessorKey:u,header:({column:c})=>{const h=c.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>c.toggleSorting(c.getIsSorted()==="asc"),children:[u,h==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):h==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(u=>e.jsx(t.TableRow,{className:"",children:u.headers.map(c=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:c.isPlaceholder?null:t.flexRender(c.column.columnDef.header,c.getContext())},c.id))},u.id))}),e.jsx(t.TableBody,{children:(l=i.getRowModel().rows)!=null&&l.length?i.getRowModel().rows.map(u=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":u.getIsSelected()&&"selected",children:u.getVisibleCells().map(c=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(c.column.columnDef.cell,c.getContext())},c.id))},u.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ia({card:s}){var k,T,E,y,C,b,w,I,D,S,F;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),l=t.getTokenParams(i==null?void 0:i.accessToken),u=t.useDashboardStore(O=>O.themeStyle),c={colors:((T=(k=u==null?void 0:u.chart)==null?void 0:k.dataset)==null?void 0:T.backgroundColor)||[]};(E=s.customCardPreferences)!=null&&E.inputData;const{getCard:h}=t.useCustomVisual(((y=s.customCardPreferences)==null?void 0:y.url)||""),d=((C=s.customCardPreferences)==null?void 0:C.visualType)||"single",x=t.useEditorStore(O=>O.frame),{setCustomCardPreferences:j}=t.useEditorActions(),{data:p}=t.useDashboardCardQuery(s),g=L.useCallback((O,A)=>{o(N=>({...N,[O]:A}))},[]);if(!((b=s.customCardPreferences)!=null&&b.componentName))return null;const m=h((w=s.customCardPreferences)==null?void 0:w.componentName);function v(O){n(O)}const f=Object.keys(((I=s.customCardPreferences)==null?void 0:I.dataInputCardIds)||{}).map(O=>{var M,z,R;const A=(z=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:z[O].cardId,N=(R=x==null?void 0:x.cards)==null?void 0:R.find(q=>q.id===A);return N||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[m&&d==="single"&&e.jsx(m,{params:l,theme:c,settings:(D=s.customCardPreferences)==null?void 0:D.settings,onDataChange:g,data:(p==null?void 0:p.records)||[]}),m&&d==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=s.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(O=>{var M,z,R;const A=(z=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:z[O].cardId,N=(R=x==null?void 0:x.cards)==null?void 0:R.find(q=>q.id===A);if(N)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:g,dataInputIndex:O,card:N},N.id+O)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(m,{theme:c,onDataChange:g,settings:f.map(O=>{var A;return(A=O==null?void 0:O.customCardPreferences)==null?void 0:A.settings}),data:f.map(O=>O!=null&&O.id?r==null?void 0:r[O.id]:[])})})]})]},(F=s.customCardPreferences)==null?void 0:F.componentName)})}function us({className:s,...a}){var v;const n=t.useEditorStore(f=>f.card),r=((v=n.customCardPreferences)==null?void 0:v.showCardHeader)??!0,o=t.useEditorStore(f=>f.frame),i=t.useDashboardStore(f=>f.dashboard.filters);t.useEditorStore(f=>f.actions.setRunSql);const{updateFilter:l}=t.useDashboardActions(),u=i==null?void 0:i.find(f=>f.id===o.filterId),{data:c,isLoading:h,isFetching:d}=t.useDashboardCardQuery(n),{setCard:x}=t.useEditorActions(),{data:j}=t.useTopoJson(n),p=L.useMemo(()=>!n.id||!(c!=null&&c.records)?null:t.createChartConfig({card:n,data:c==null?void 0:c.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:j}),[n.id,c==null?void 0:c.records,n.type,n.queryConfig,n.customCfg,n.preferences,j]);function g(f){return e.jsx(ia,{card:f})}function m(){if(c!=null&&c.records&&(c==null?void 0:c.records.length)===0&&!h&&!d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No records to display"})]});if(!n.id)return null;if(n.type==="custom")return g(n);if(!["table","custom"].includes(n.type)&&p)return e.jsx(e.Fragment,{children:h||d?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:p})});if(n.type==="table"&&(c!=null&&c.records)&&(c==null?void 0:c.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(t.TableVisual,{card:n,data:c==null?void 0:c.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:f=>x({...n,title:f}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:f=>x({...n,description:f}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:u.title||u.column,onSave:f=>l({...u,title:f}),children:e.jsx(t.Label,{children:u.title})}),e.jsx(t.FilterComponent,{filter:u})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:m()})]})}const Xe=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.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:s,value:a,onChange:n}),la=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.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."})]})]}),ca=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"javascript",value:s,onChange:o})})]}),da=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function ua(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[l,u]=L.useState(""),[c,h]=L.useState(""),d=t.useEditorStore(y=>y.card),x=t.useEditorStore(y=>y.card.customCfg),j=x?JSON.stringify(x,null,2):"",{data:p}=t.useDashboardCardQuery(d),{data:g}=t.useTopoJson(d),{setCardCustomCfg:m,setCustomVisualCode:v}=t.useEditorActions(),f=y=>{var C,b;return JSON.stringify({...y,data:{...y.data,datasets:(b=(C=y.data)==null?void 0:C.datasets)==null?void 0:b.map(w=>({...w,data:[]}))}},null,2)},k=()=>{var C,b;if(!((C=p==null?void 0:p.records)!=null&&C.length))return;const y=t.createChartConfig({card:d,data:p.records,cardType:d.type,queryConfig:d.queryConfig,preferences:d.preferences,topoJson:g});if(y){r(f(y)),u(((b=d.preferences)==null?void 0:b.customVisualCode)||"");const w=t.merge(y,x);i(f(w))}},T=()=>{try{if(l&&v(l),o){const y=JSON.parse(o),C=t.getObjectDiff(JSON.parse(n),y);m(C),h("")}}catch{h("Invalid JSON configuration")}},E=Object.keys(x||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:k,className:E?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(la,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(us,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ca,{customCode:l,cardCustomCfgString:j,mergedConfig:o,onConfigChange:y=>i(y??""),onCodeChange:y=>u(y??"")})]}),e.jsx(da,{error:c,hasCardCustomConfig:!!x,onReset:()=>{i(n),m(null)},onApply:T,onClose:()=>a(!1)})]})]})}function ms(s){const[a,n]=L.useState(null);return a}function hs(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function ma({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:l}=t.useEditorActions(),{data:u}=hs();function c(h,d){r(null),o({}),i(h),d&&l({type:"component",visualType:"single",url:d.url,componentName:d.name,icon:d.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var d;if(u){const j=(await Promise.all((d=u==null?void 0:u.plugins)==null?void 0:d.map(async p=>(await t.loadManifest(p.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:p.value}))))).flat();n(j)}})()},[u]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((h,d)=>e.jsx(ha,{text:h.name,onClick:()=>c("custom",h),icon:h.icon},h.url+h.name+d))})]})}const ha=({text:s,icon:a,onClick:n})=>{const r=ms(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function wt(s){return je({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:[]}]})(s)}function xa(s){return je({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:[]}]})(s)}function kt(s){return je({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:[]}]})(s)}function Et(s){return je({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:[]}]})(s)}function It(s){return je({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:[]}]})(s)}function Dt(s){return je({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:[]}]})(s)}function xs({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(d=>d.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(d,x){i(null),r({}),n(d),["kpi","custom","text","map"].includes(d)&&(o(!0),u(void 0)),s==null||s()}const h=1e3;return e.jsxs("div",{className:"grid grid-cols-4 place-items-center",children:[e.jsx(t.IconButton,{openDelay:h,tooltip:"Table",onClick:()=>c("table"),className:"h-10 p-4",children:e.jsx(He,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bar Chart",onClick:()=>c("bar"),className:"h-10 p-4",children:e.jsx(Ge,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Line Chart",onClick:()=>c("line"),className:"h-10 p-4",children:e.jsx($e,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Bar Chart",onClick:()=>c("stackedBar"),className:"h-10 p-4",children:e.jsx(dt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Line Chart",onClick:()=>c("stackedLine"),className:"h-10 p-4",children:e.jsx(It,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Scatter Chart",onClick:()=>c("scatter"),className:"h-10 p-4",children:e.jsx(xt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bubble Chart",onClick:()=>c("bubble"),className:"h-10 p-4",children:e.jsx(kt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Pie Chart",onClick:()=>c("pie"),className:"h-10 p-4",children:e.jsx(ht,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Doughnut Chart",onClick:()=>c("doughnut"),className:"h-10 p-4",children:e.jsx(pt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Funnel Chart",onClick:()=>c("funnel"),className:"h-10 p-4",children:e.jsx(Et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Radar Chart",onClick:()=>c("radar"),className:"h-10 p-4",children:e.jsx(yt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Polar Area Chart",onClick:()=>c("polarArea"),className:"h-10 p-4",children:e.jsx(wt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Tornado Chart",onClick:()=>c("tornado"),className:"h-10 p-4",children:e.jsx(vt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>c("range"),className:"h-10 p-4",children:e.jsx(mt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"KPI",onClick:()=>c("kpi"),className:"h-10 p-4",children:e.jsx(Dt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Text",onClick:()=>c("text"),className:"h-10 p-4",children:e.jsx(Jt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>c("map"),className:"h-10 p-4",children:e.jsx(jt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Custom",onClick:()=>c("custom"),className:"h-10 p-4",children:e.jsx(bt,{className:t.cn("size-5",a)})})]})}function pa({chartType:s,className:a,customIcon:n,componentName:r}){const o=ms();switch(s){case"bar":return e.jsx(Ge,{className:a});case"line":return e.jsx($e,{className:a});case"pie":return e.jsx(ht,{className:a});case"radar":return e.jsx(yt,{className:a});case"scatter":return e.jsx(xt,{className:a});case"bubble":return e.jsx(kt,{className:a});case"doughnut":return e.jsx(pt,{className:a});case"stackedBar":return e.jsx(dt,{className:a});case"stackedLine":return e.jsx(It,{className:a});case"polarArea":return e.jsx(wt,{className:a});case"funnel":return e.jsx(Et,{className:a});case"tornado":case"pyramid":return e.jsx(vt,{className:a});case"range":return e.jsx(mt,{className:a});case"kpi":return e.jsx(Dt,{className:a});case"text":return e.jsx(Zt,{className:a});case"map":return e.jsx(jt,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(bt,{className:a});default:return e.jsx(He,{className:a})}}function fa({variant:s="ghost"}){var i,l;const[a,n]=L.useState(!1),r=t.useEditorStore(u=>u.card),o=r.type;return t.useDashboardStore(u=>u.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(pa,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(l=r.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:u=>u.preventDefault(),className:"w-50",children:[e.jsx(xs,{onChartTypeChange:()=>n(!1)}),e.jsx(ma,{onChartTypeChange:()=>n(!1)})]})]})}const Ae="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function _t(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ga(){var M,z,R,q,B,K;const[s,a]=L.useState(!1),n=t.useEditorStore(J=>{var $;return($=J.card)==null?void 0:$.preferences}),r=t.useEditorStore(J=>{var $;return($=J.card)==null?void 0:$.type}),o=t.getNumberAxis(n,{}),[i,l]=L.useState(_t(n,r)),[u,c]=L.useState(((R=(z=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:z[o])==null?void 0:R.min)||""),[h,d]=L.useState(((K=(B=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:B[o])==null?void 0:K.max)||""),[x,j]=L.useState(u||h?"custom":"auto"),[p,g]=L.useState(""),[m,v]=L.useState(0),[f,k]=L.useState(""),[T,E]=L.useState(""),[y,C]=L.useState(""),b=t.useEditorStore(J=>J.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),I=t.useEditorStore(J=>J.card),D=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var J,$,U,G,V,P,H,Y,Z,_,Q,se,ue,Me;l(_t(n,r)),c(((U=($=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:$[o])==null?void 0:U.min)===0?0:""),d(((P=(V=(G=n==null?void 0:n.chartOptions)==null?void 0:G.scales)==null?void 0:V[o])==null?void 0:P.max)||""),g(((_=(Z=(Y=(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales)==null?void 0:Y[o])==null?void 0:Z.ticks)==null?void 0:_.stepSize)||""),v(((Q=n==null?void 0:n.numberAxisFormat)==null?void 0:Q.decimalPlaces)||0),k(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.suffix)||""),E(((ue=n==null?void 0:n.numberAxisFormat)==null?void 0:ue.currency)||""),C(((Me=n==null?void 0:n.numberAxisFormat)==null?void 0:Me.locale)||"")},[s,n,o,r]);function S(J,$){return $===""||/^[0-9\b]+$/.test($)?Number($):Number(J)}function F(){const J=[...new Set(t.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(t.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(t.Select,{value:T||"none",onValueChange:$=>E($==="none"?"":$),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),J.map($=>e.jsx(t.SelectItem,{value:$,children:$},$))]})})]}),e.jsxs(t.Select,{value:y,onValueChange:$=>C($),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map($=>e.jsx(t.SelectItem,{value:$.locale,children:$.locale},$.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:m,onChange:$=>v(Number($.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ae}`})]})]})}function O(){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(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:D,value:i,onValueChange:J=>l(J),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:D,id:"scale-option",value:x,onValueChange:J=>j(J),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.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(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),x==="custom"&&i=="linear"&&A()]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:u,onChange:J=>c($=>S($,J.target.value)),className:`col-span-1 h-8 w-full ${Ae}`}),e.jsx(t.Input,{value:h,onChange:J=>d($=>S($,J.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ae}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:p,onChange:J=>g($=>S($,J.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ae}`})]})]})}function N(){var G;let J={};x==="custom"&&(J={min:u,max:h,ticks:{stepSize:p}});const $={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(G=n==null?void 0:n.chartOptions)==null?void 0:G.scales,[o]:{type:i,...i==="linear"?J:{}}}},numberAxisFormat:{decimalPlaces:m,suffix:f,currency:T,locale:y}};console.log($),b($);const U={...I,preferences:$};w(U)}return e.jsxs(t.Popover,{onOpenChange:J=>a(J),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(on,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",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:[F(),O(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:N,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function ja(){const s=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.position}),a=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.align}),n=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.display}),{setLegendOptions:r}=t.useEditorActions(),o=u=>{r({display:u,position:s,align:a})},i=u=>{r({display:n,position:u,align:a})},l=u=>{r({display:n,position:s,align:u})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(gn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"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(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.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(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(_e,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Gs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(qe,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx($s,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>l("start"),children:e.jsx(Rs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>l("center"),children:e.jsx(Bs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>l("end"),children:e.jsx(Ps,{className:"size-4"})})]})]})]})]})]})})]})}function ya(){const s=t.useEditorStore(i=>{var l,u;return(u=(l=i.card.preferences)==null?void 0:l.chartOptions)==null?void 0:u.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(Bt,{className:"size-4"}):e.jsx(zt,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Bt,{className:"size-4"}):e.jsx(zt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function ps(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>l.isShowingVisual),n=t.useEditorStore(l=>{var u,c;return(c=(u=l.card)==null?void 0:u.preferences)==null?void 0:c.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const l=["xy","none","x","y"],c=(l.indexOf(r)+1)%l.length;o(l[c])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(ya,{}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ga,{}),e.jsx(ja,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(xn,{className:"size-4"}),r==="x"&&e.jsx(nn,{className:"size-4"}),r==="y"&&e.jsx(Dn,{className:"size-4"}),r==="none"&&e.jsx(An,{className:"size-4"})]})]}):null}function ba(){const s=t.useEditorStore(g=>g.frame),a=t.useEditorStore(g=>g.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),l=(g,m)=>{g.dataTransfer.setData("tabIndex",m.toString())},u=g=>{g.preventDefault()},c=(g,m)=>{const v=g.dataTransfer.getData("tabIndex");if(v===m.toString())return;const f=Array.from(s.cards),[k]=f.splice(parseInt(v),1);f.splice(m,0,k),n({...s,cards:f})};function h(g){const m=s.cards.filter(k=>k.id!==g),v=m[0],f={...s,cards:m,activeCardId:v.id};n(f),r(v.id),o(v)}function d(g,m){const v={...s,cards:[...s.cards,m],activeCardId:g.id};n(v),r(m.id)}function x(){const g={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};d(a,g)}function j(g){const m={connectionId:g.connectionId,lastSelectedDatabase:g.lastSelectedDatabase,lastSelectedSchema:g.lastSelectedSchema,lastSelectedTable:g.lastSelectedTable,lastSelectedDatamodelId:g.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};d(g,m)}function p(g,m){return g.cards.length===1&&(m.displayTab===!0||m.displayTab===void 0)||g.activeCardId!==m.id&&(m.displayTab===!0||m.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=m.displayTab===void 0?!1:!m.displayTab;o({...m,displayTab:v}),i({...m,displayTab:v})},children:m.displayTab===!0||m.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ln,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((g,m)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:v=>l(v,m),onDragOver:u,onDrop:v=>c(v,m),className:"",value:g.id,children:[p(s,g),e.jsx(t.Editable,{enabled:s.activeCardId===g.id,text:g.tabTitle||g.title,onSave:v=>{o({...a,tabTitle:v}),i({...a,tabTitle:v})},children:g.tabTitle||g.title},g.id),s.activeCardId===g.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>h(g.id)})]},g.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>j(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:x,children:e.jsx(rn,{className:"h-4 w-4"})})]})})}function fs(){const s=t.useEditorStore(m=>m.frame),a=t.useEditorStore(m=>m.card),n=t.useEditorStore(m=>m.isSqlRunning),r=t.useEditorStore(m=>m.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:l,setIsDevMode:u,setRunSql:c}=t.useEditorActions(),{data:h,isLoading:d,isFetching:x}=t.useDashboardCardQuery(a);function j(m){const v=s.cards.find(f=>f.id===m);if(v!=null&&v.sql){r||u(!0),i(m);return}if(v!=null&&v.queryConfig){r&&u(!1),p(m),i(m);return}r||p(m),i(m)}function p(m){const v={...s,cards:s.cards.map(k=>k.id===a.id?a:k),activeCardId:m};o(v);const f=v.cards.find(k=>k.id===m);f.sql&&c(!0),l(f)}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(t.KPICard,{card:a,data:h==null?void 0:h.records,isPending:d})})}):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(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:h==null?void 0:h.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(us,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:j,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(m=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:m.id,children:g()},m.id)),e.jsx(ba,{})]})}function Le({children:s}){var k;t.useEditorStore(T=>T.frame);const a=t.useEditorStore(T=>T.card),n=t.useEditorStore(T=>T.isDevMode),r=t.useEditorStore(T=>T.isShowingVisual),o=t.useDashboardStore(T=>T.isVisualEditing),i=t.useEditorStore(T=>T.pythonStdOut);t.useEditorStore(T=>T.actions.setRunSql);const{setFrame:l,setCard:u,setActiveTabCardId:c,runAssistant:h,setIsDevMode:d}=t.useEditorActions(),{data:x,isLoading:j,isFetching:p,error:g}=t.useDashboardCardQuery(a);function m(){const T=JSON.stringify(x==null?void 0:x.records,null,2),E=new Blob([T],{type:"application/json"}),y=URL.createObjectURL(E),C=document.createElement("a");C.href=y,C.download=`${a.title}.json`,C.click()}function v(){const E=[Object.keys(x==null?void 0:x.records.reduce((w,I)=>({...w,...I}),{})).join(","),...((x==null?void 0:x.records)||[]).map(w=>Object.values(w).join(","))].join(`
404
- `),y=new Blob([E],{type:"text/csv"}),C=URL.createObjectURL(y),b=document.createElement("a");b.href=C,b.download=`${a.title}.csv`,b.click()}function f(){const T=`Can you get the documentation for ${a.type} chart?`;h(T)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(j||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(ce,{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(fa,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:f,children:e.jsx(Ys,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(ua,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.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(xa,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:m,children:e.jsx(dn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(x==null?void 0:x.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:[s,e.jsx(ps,{})]}),n&&e.jsx(Ca,{})]}),r?e.jsx(fs,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(va,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(oa,{data:(x==null?void 0:x.records)||[]}),(g||(x==null?void 0:x.error))&&e.jsx("span",{className:"font-mono text-xs",children:(g==null?void 0:g.message)||((k=x==null?void 0:x.error)==null?void 0:k.message)})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function va(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.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(t.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(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ca(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Na(){var m,v;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=hs(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),o=t.useEditorStore(f=>f.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:l}=t.useEditorActions(),{components:u,manifest:c}=t.useCustomVisual((s==null?void 0:s.url)||""),h=(m=c==null?void 0:c.visuals)==null?void 0:m.find(f=>f.name===(s==null?void 0:s.componentName));function d(f,k){if(!s)return;const E={...(s==null?void 0:s.dataInputCardIds)||{},[f]:{cardId:k,hookRef:null}};l({...s,dataInputCardIds:E})}function x(f){var T,E;const k=(T=o==null?void 0:o.cards)==null?void 0:T.filter(y=>{var C;return((C=y==null?void 0:y.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(y=>({value:y.id,label:y.tabTitle||y.title}));return e.jsx("div",{className:"space-y-2",children:(E=f==null?void 0:f.dataInputs)==null?void 0:E.map((y,C)=>{var b,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:y}),e.jsx(le,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((w=(b=s==null?void 0:s.dataInputCardIds)==null?void 0:b[C])==null?void 0:w.cardId)||"",onValueChange:I=>d(C,I)})]},C+Math.random())})})}function j(f,k,T=[],E=""){var y,C;return s?f==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((y=s==null?void 0:s.settings)==null?void 0:y[k])||E,onChange:b=>{l({...s,settings:{...s==null?void 0:s.settings,[k]:b.target.value}})}},k):f==="select"?e.jsx(le,{className:"h-8 w-full",label:"",options:T,value:((C=s==null?void 0:s.settings)==null?void 0:C[k])||E,onValueChange:b=>{l({...s,settings:{...s==null?void 0:s.settings,[k]:b}})}}):null:null}function p(f){const k=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([T,E])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:E.title}),j(E.ui,T,E.options,E.defaultValue)]},T))})}function g(f){s&&l({...s,visualType:f,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.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(le,{icon:e.jsx(Us,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:f=>l({...s||{url:"",componentName:""},url:f})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:g,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:u&&e.jsx(le,{icon:e.jsx(an,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.filter(f=>f.type===i).map(f=>({value:f.name,label:f.name})))||[],value:s.componentName,onValueChange:f=>{console.log("changing value",f),l({...s,componentName:f})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[h&&h.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:x(h)})]}),h&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(h)})})]})]})]})}function ye(){const[s,a]=L.useState([]),n=t.useEditorStore(h=>h.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(h=>h.actions),i=t.useEditorStore(h=>h.queryResultColumns);t.useEditorStore(h=>{var d;return(d=h.card.preferences)==null?void 0:d.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(h,d){var x,j;d?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:h,expression:""}]}):o({...n,onClickFilter:[{columnIndex:h,expression:""}]}):(o({...n,onClickFilter:(j=n==null?void 0:n.onClickFilter)==null?void 0:j.filter(p=>p.columnIndex!==h)}),a(p=>{const g=[...p];return g[h]=!1,g}))}function u(h,d){var j;const x=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.map(p=>p.columnIndex===h?{...p,expression:d.target.value}:p);o({...n,onClickFilter:x})}function c(h){var d,x,j,p;if(s!=null&&s[h]||(x=(d=n==null?void 0:n.onClickFilter)==null?void 0:d.find(g=>g.columnIndex===h))!=null&&x.expression)return e.jsx(t.Input,{value:(p=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(g=>g.columnIndex===h))==null?void 0:p.expression,onChange:g=>u(h,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(t.Label,{children:"On Click"}),i==null?void 0:i.map((h,d)=>{var x,j;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(t.Checkbox,{checked:!!((x=n==null?void 0:n.onClickFilter)!=null&&x.find(p=>p.columnIndex===d)),onCheckedChange:p=>l(d,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:h}),e.jsx("div",{className:"flex items-center gap-2",children:((j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(p=>p.columnIndex===d))&&e.jsx(t.Pencil,{onClick:()=>{a(p=>{const g=[...p];return g[d]=!p[d],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),c(d)]})},h)})]})}function Sa({idx:s}){var u;const a=t.useEditorStore(c=>{var h;return(h=c.card)==null?void 0:h.preferences}),n=t.useEditorStore(c=>{var h;return(h=c.card.preferences)==null?void 0:h.datasetOptions}),r=t.useEditorStore(c=>c.actions.setCardPreferences),o=(u=a==null?void 0:a.chartOptions)==null?void 0:u.indexAxis,i=n==null?void 0:n.find(c=>c.idx===s);function l(c,h){(c==="end"||c==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const d={display:c!=="none",align:c,anchor:c,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:h,datalabels:d}]});else{const x={...i};x.datalabels=d;const j=n==null?void 0:n.map(p=>p.idx===h?x:p);r({...a,datasetOptions:j})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Wt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(jn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(bn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function gs(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);o=l.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ve({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function js(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var h,d,x;return(x=(d=(h=c==null?void 0:c.card)==null?void 0:h.preferences)==null?void 0:d.chartOptions)==null?void 0:x.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:l,keys:u}=gs();return u.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(c=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:c,children:ys(c)},c))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:l.map((c,h)=>e.jsx(bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:c,idx:h},c))})]})]})}function ys(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function bs({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(d=>{var x;return(x=d.card)==null?void 0:x.preferences}),l=t.useEditorStore(d=>{var x,j;return(j=(x=d.card)==null?void 0:x.preferences)==null?void 0:j.datasetOptions}),u=l==null?void 0:l.find(d=>d.idx===a),{setCardPreferences:c}=t.useEditorStore(d=>d.actions);function h(d){if(!u)c({...i,datasetOptions:[...l||[],{idx:a,type:d==="area"?"line":d,fill:d==="area"?"origin":""}]});else{const x={...u};x.type=d==="area"?"line":d,x.fill=d==="area"?"origin":"";const j=l==null?void 0:l.map(p=>p.idx===a?x:p);c({...i,datasetOptions:j})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ve,{className:"max-w-[100px]",title:s,children:ys(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ge,{onClick:()=>h("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx($e,{onClick:()=>h("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Xs,{onClick:()=>h("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Sa,{idx:a})]})]})}function vs(){const s=t.useEditorStore(p=>p.selectedConnectionId),a=t.useEditorStore(p=>p.selectedDatamodelId),n=t.useEditorStore(p=>p.selectedDatabaseName),r=t.useEditorStore(p=>p.selectedSchemaName),o=t.useEditorStore(p=>p.selectedTableName),i=t.useDashboardStore(p=>p.dashboard.filters)||[],l=t.useDashboardStore(p=>p.actions.addFilter),u=t.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:c}=t.useDashboardActions(),{modelItems:h,tableName:d,connectionType:x}=t.useEditorAside();function j(p,g="dashboard"){var b;const m=t.fmt(p.column_name),v=t.fmt(n||""),f=t.fmt(r||""),k=t.fmt(d);let T=t.getQualifiedTableName({schemaName:f,tableName:k,connectionType:x,databaseName:v}),E=`${T}.${m}`;const y=(b=h==null?void 0:h.find(w=>w.id===a))==null?void 0:b.name;a&&a!=="none"&&(E=`${t.DATAMODEL_NAMESPCACE}.${y}.${m}`,T=`${t.DATAMODEL_NAMESPCACE}.${y}`);const C=i==null?void 0:i.find(w=>w.column===E&&w.table===k&&(w.database===v||w.database===n));if(C)c(C.id),u(C.id);else{const w=t.v4();return d==="api"&&s?(l({location:g,id:w,column:E,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(p.data_type,T,m)}),w):(l({id:w,location:g,column:E,title:p.column_name,dataType:p.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(p.data_type,T,m)}),w)}}return{assignFilter:j}}function Se(){const s=t.useDashboardStore(u=>u.dashboard.filters),a=t.useEditorStore(u=>u.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=vs();function i(u){const c=o(u,"frame");n({...a,filterId:c})}const l=s==null?void 0:s.find(u=>u.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(wa,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function wa({columns:s,onSelect:a}){var l;const[n,r]=re.useState(!1),[o,i]=re.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(l=s.find(u=>u.column_name===o))==null?void 0:l.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(u=>e.jsxs(t.CommandItem,{value:u.column_name,onSelect:c=>{const h=c===o?"":c;i(h),r(!1),h&&a(u)},children:[u.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===u.column_name?"opacity-100":"opacity-0")})]},u.column_name))})]})]})})]})}function ka({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(js,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ye,{}),e.jsx(Se,{})]})]})]})})}function Tt(){var o,i,l;const s=t.useEditorStore(u=>u.card.type),a=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:n}=t.useEditorStore(u=>u.actions);function r(u){var d;const c={datalabels:{display:u!=="none",align:u,anchor:u,clamp:!0}},h={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins,...c}}};n(h),console.log(u)}return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((l=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.datalabels)==null?void 0:l.anchor)||"none",onValueChange:r,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function Ea({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Tt,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ye,{}),e.jsx(Se,{})]})]})]})})}const Ia={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Da={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Ta(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:Ma(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Tt,{}),e.jsx(ye,{}),e.jsx(Se,{})]})]})}function Ma(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.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(Ia,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.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(Da,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.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(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.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(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.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 Aa(){var c,h,d,x,j;const s=t.useEditorStore(p=>p.card.preferences),a=t.useEditorStore(p=>p.actions.setCardPreferences),n=t.useEditorStore(p=>p.actions.setNumberFormat);t.useEditorStore(p=>{var g,m;return(m=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:m.decimalPlaces});const r=t.useEditorStore(p=>{var g,m;return(m=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:m.locale}),o=t.useEditorStore(p=>{var g,m;return(m=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:m.currency});t.useEditorStore(p=>p.actions.setFilterOnClickField);const i=t.useEditorStore(p=>{var g,m;return(m=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:m.colorRanges})||[],l=t.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((c=s==null?void 0:s.formatNumber)!=null&&c.enabled),onCheckedChange:p=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:p}})}}),e.jsx(t.Label,{children:"Format Number"})]}),((h=s==null?void 0:s.formatNumber)==null?void 0:h.enabled)===!0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:r||"none",onValueChange:p=>{var g,m,v;return n(((g=s==null?void 0:s.formatNumber)==null?void 0:g.decimalPlaces)||0,((m=s==null?void 0:s.formatNumber)==null?void 0:m.currency)||"",p,((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),t.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(t.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:p=>{var g,m,v;console.log("currency",p),n(((g=s==null?void 0:s.formatNumber)==null?void 0:g.decimalPlaces)||0,p==="none"?"":p,((m=s==null?void 0:s.formatNumber)==null?void 0:m.locale)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(t.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((x=(d=s==null?void 0:s.formatNumber)==null?void 0:d.decimalPlaces)==null?void 0:x.toString())||"0",onValueChange:p=>{var g,m,v;return n(Number(p),((g=s==null?void 0:s.formatNumber)==null?void 0:g.currency)||"",((m=s==null?void 0:s.formatNumber)==null?void 0:m.locale)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(t.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((j=s==null?void 0:s.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var g,m,v;return n(((g=s==null?void 0:s.formatNumber)==null?void 0:g.decimalPlaces)||0,((m=s==null?void 0:s.formatNumber)==null?void 0:m.currency)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.locale)||"",p.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(t.ColorFormat,{colorRanges:i,setColorRanges:l})]})]})}function La(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.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:s=>s.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(Aa,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ze({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.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(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const Oa=[{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"}],Fa=["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"],za=Fa.map(s=>({label:s,value:s}));function Ba(){var c,h,d,x,j,p,g,m,v,f,k,T,E,y,C,b,w,I;const s=t.useEditorStore(D=>D.card),a=(h=(c=s==null?void 0:s.preferences)==null?void 0:c.mapVisualOptions)==null?void 0:h.topoJsonUrl,[n,r]=L.useState(((x=(d=s==null?void 0:s.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(D=>({label:D,value:D}))||[],u=[{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(Ze,{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(t.Separator,{className:"my-4"}),e.jsx(Ze,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(le,{className:"h-9",options:u,onValueChange:D=>{console.log("value",D),o({...s.preferences,mapVisualOptions:{topoJsonUrl:D}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:D=>{r(D.target.value)},onBlur:()=>{var D;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(D=s.preferences)==null?void 0:D.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(le,{className:"h-9",options:l,value:((p=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,objectKey:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(le,{className:"h-9",options:Oa,value:((m=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:m.projection)||"",label:"Projection",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projection:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(le,{className:"h-9",options:za,value:((f=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,colorScale:D}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Ze,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((T=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(D.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((C=(y=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:C[0])||0,onChange:D=>{var S,F,O,A;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(D.target.value),((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(w=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:I[1])||0,onChange:D=>{var S,F,O,A;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[0])||0,Number(D.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ye,{})]})}function Ra(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.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(t.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(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Tt,{}),s==="text"&&e.jsx(Ra,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ye,{}),e.jsx(Se,{})]})]})]})})}function Pa(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(le,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(js,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ye,{}),e.jsx(Se,{})]})]})]})})}function Va({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.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(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ye,{}),e.jsx(Se,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.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 qa=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:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),_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 y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ga=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:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function $a(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Pa,{});case"tornado":case"pyramid":return e.jsx(Oe,{docContent:qa,cardType:n});case"kpi":return e.jsx(La,{});case"line":case"bar":return e.jsx(ka,{cardType:n});case"range":return e.jsx(Oe,{docContent:_a,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Oe,{cardType:n});case"bubble":case"scatter":return e.jsx(Ea,{cardType:n});case"table":return e.jsx(Va,{cardType:n});case"text":return e.jsx(Oe,{docContent:Ga,cardType:n,suffix:"Visual"});case"map":return e.jsx(Ba,{});case"custom":return e.jsx(Na,{});default:return e.jsx(Ta,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Cs({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(l=>l.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(l=>l.value===a.granularity)||n[0]);function i(l){r(l)}return e.jsx(le,{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:l=>i(l),label:s,showPlaceholderLabel:!1})}const Ha=[{label:"Sum",value:"SUM",logo:e.jsx(Qt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(gt,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(mn,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(_s,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(qe,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(_e,{className:"size-3.5"})}];function Ja({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ha;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:ke(s.name,o)};a(s.id,i)}return e.jsx(Cs,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Ua=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Ya({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:Ne(s.name,r)};a(s.id,o)}return e.jsx(Cs,{column:s,functions:Ua,onFunctionChange:r=>n(r),label:"Granularity"})}function Ka({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let u=[];(n===pe||n===fe||n===ge)&&(u=r);const c=u==null?void 0:u.filter(h=>h.column_name!==s.name);return c==null?void 0:c.map(h=>({id:h.column_name,value:h.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function l(u){const c=r==null?void 0:r.find(h=>{var d;return h.column_name===((d=u[0])==null?void 0:d.id)});c&&a(c)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:l,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:s.name})}function Qa({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions(),{transformedMetricKeys:n,dimensionKeys:r}=gs();console.log(n,r);const o=t.useEditorStore(c=>{var h;return(h=c.card.queryConfig)==null?void 0:h.pivotColumns}),i=!!(o&&o.length>0),l=n.find(c=>c===s.label||c===s.name),u=l?n.indexOf(l):-1;return e.jsxs("div",{className:"space-y-3",children:[l&&e.jsx(bs,{idx:u,col:l,children:e.jsx(t.Editable,{enabled:!0,className:"w-[130px]",text:s.label||"",placeholder:"Enter label",onSave:c=>{a(s.id,{...s,label:c||s.name})},children:e.jsx(Ve,{className:"w-[130px]",children:s.label||s.name})})}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(t.Label,{children:"Pivot Header"}),e.jsx(t.Editable,{enabled:!0,text:s.aliasTemplate||"",placeholder:"{label} ({pivot})",onSave:c=>{a(s.id,{...s,aliasTemplate:c||""})},children:e.jsx(Ve,{className:"font-mono text-xs text-muted-foreground",children:s.aliasTemplate||"{label} ({pivot})"})})]})]})}function Wa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:l,updateMetricColumnOld:u,updatePivotByColumnOld:c}=t.useEditorActions(),{attributes:h,listeners:d,setNodeRef:x,transform:j,transition:p,isDragging:g}=t.useSortable({id:s.id,data:{type:a}}),m=j?{opacity:g?.5:void 0,transform:t.CSS.Translate.toString(j),transition:p}:void 0,v=t.isTextDataType(s.type);function f(C){const b=t.isNumberDataType(C.data_type),w=t.isTextDataType(C.data_type),I=t.isDateDataType(C.data_type),D=b?"number":w?"string":I?"date":"string";if(r===pe){if(w){const S={id:s.id,name:C.column_name,type:D,role:"groupby"};l(s.id,S)}if(I){const S={id:s.id,name:C.column_name,type:D,role:"groupby",label:Ne(C.column_name,"month"),granularity:"month"};l(s.id,S)}}if(r===ge){if(w){const S={id:s.id,name:C.column_name,type:D,role:"groupby"};c(s.id,S)}if(I){const S={id:s.id,name:C.column_name,type:D,label:Ne(C.column_name,"month"),granularity:"month",role:"groupby"};c(s.id,S)}}if(r===fe){const S={id:s.id,name:C.column_name,type:D,role:"metric",label:ke(C.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};u(s.id,S)}}function k(){if(r===fe)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(Qa,{column:s})})}function T(){const C=t.isDateDataType(s.type);if(r===fe)return e.jsx(Ja,{column:s});if((r===pe||r===ge)&&C)return e.jsx(Ya,{column:s})}function E(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===pe||r===ge)&&v}),children:e.jsx(Ka,{col:s,onChange:f,droppableId:r})})}function y(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(Mn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Yt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...d,...h,ref:x,style:m,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:[y(),T(),E()]}),o&&k()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function et({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var m,v;const{setNodeRef:l,isOver:u,over:c}=t.useDroppable({id:s}),h=t.useDndStore(f=>f.activeId),d=t.useEditorStore(f=>{var k;return(k=f.card)==null?void 0:k.type}),x=u||((v=(m=c==null?void 0:c.data)==null?void 0:m.current)==null?void 0:v.type)===o,j=h?r:n,p=o===ze?"Rows":o===Be?"Pivot Columns":"Columns";function g(){if(!j||j.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(t.SortableContext,{items:n==null?void 0:n.map(f=>f.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",x&&"border border-muted-foreground/20"),ref:l,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),d!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:p})]}),g(),e.jsx("div",{className:"space-y-2",children:j==null?void 0:j.map(f=>f.id===as.id?e.jsx(Xa,{},f.id):e.jsx(Wa,{droppableId:s,type:o,column:f,onRemoveColumn:i},f.id))})]})})}function Xa(){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 Ns({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:l,transition:u,isDragging:c}=t.useSortable({id:a,data:{type:n}}),h=l?{opacity:c?.5:void 0,transform:t.CSS.Translate.toString(l),transition:u}:void 0;return e.jsx("div",{...o,...r,ref:i,style:h,children:s})}function Za(){const s=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.orderBy})||[],a=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.groupByColumns})||[],n=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),l=[...a,...n];if(l.length===0)return e.jsx(e.Fragment,{});const u=e.jsx(Js,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),c=e.jsx(qs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Hs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Vs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),x=l==null?void 0:l.filter(f=>!s.some(k=>k.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function j(f,k){const T=p(f);return T?T.role==="metric"?k==="asc"?h:d:k==="asc"?u:c:null}function p(f){return l.find(k=>k.id===f)}function g(f){const k=s.find(T=>T.columnId===f);if(k){const T={...k,direction:k.direction==="asc"?"desc":"asc"};i(T)}}const m=f=>{r({columnId:f.id,direction:"asc"})};function v(f){const k=s.find(T=>T.columnId===f);k&&o(k)}return e.jsx(t.SortableContext,{items:s.map(f=>we(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),x.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:x,selectedOptions:[],onChange:f=>m(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(f=>{var k,T;return e.jsx(Ns,{id:we(f.columnId),type:St,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(Yt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ve,{className:"w-[175px] text-sm",children:((k=p(f.columnId))==null?void 0:k.label)||((T=p(f.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>g(f.columnId),className:"rounded-sm p-0",children:j(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(f.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},we(f.columnId))})]})})}function er(){const s=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),a=t.useEditorStore(v=>v.card.type),n=t.useDndStore(v=>v.previewGroupByColumns),r=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=t.useDndStore(v=>v.previewMetricColumns),i=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),l=t.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:u,removeColumnFromMetricColumns:c,removeColumnFromPivotBy:h}=t.useEditorActions();function d(v){u(v)}function x(v){c(v)}function j(v){h(v)}let p="Group By",g="Metrics",m="Stack By";return a==="table"&&(p="Rows",g="Metrics",m="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(xs,{iconClassName:"size-[19px]"}),e.jsxs(t.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(et,{onRemoveColumn:d,sortableType:ze,id:pe,label:p,columns:s,previewColumns:n}),e.jsx(et,{onRemoveColumn:j,sortableType:Be,id:ge,label:m,columns:i,previewColumns:l}),e.jsx(et,{onRemoveColumn:x,sortableType:it,id:fe,label:g,columns:r,previewColumns:o}),e.jsx(Za,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Mt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,l]=L.useState(!1),{removeEditorFilter:u,clearEditorFilter:c}=t.useEditorActions(),h=t.useEditorStore(x=>{var j,p;return(p=(j=x.card.queryConfig)==null?void 0:j.filters)==null?void 0:p.some(g=>g.filterColumnName===a.name)});function d(x){u(x)}return e.jsx(Ns,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),h&&e.jsx("button",{onClick:()=>c(a),children:e.jsx(t.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:()=>d(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.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:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function tr({column:s,sortableType:a}){const n=t.useDashboardStore(T=>T.themeStyle),r=t.useEditorStore(T=>{var E,y;return(y=(E=T.card)==null?void 0:E.queryConfig)==null?void 0:y.filters}),o=t.useEditorStore(T=>{var E,y;return(y=(E=T.card.queryConfig)==null?void 0:E.filterColumns)==null?void 0:y.find(C=>C.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:l,selectedTableName:u}=t.useEditorAside(),c=L.useMemo(()=>{var T;return(T=r==null?void 0:r.find(E=>E.filterColumnName===s.name))==null?void 0:T.filterValue},[r,s.name]),h=L.useMemo(()=>Array.isArray(c)?c.map(T=>({id:T,value:T})):[],[c]),{updateEditorFilterValue:d}=t.useEditorActions(),x={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:j,isLoading:p,isFetching:g,isError:m}=t.useFilterQuery(x),v=L.useMemo(()=>{var E;return x.column?(E=j==null?void 0:j.records)==null?void 0:E.map(y=>{let C=x.column.split(".").slice(-1)[0].replace(/"/g,"");return y[C]===void 0&&(C=C.toLowerCase()),{id:y[C],value:y[C]}}):[]},[j,x.column]);function f(T){const E=T.map(y=>y.id);d(s.name,E)}function k(){return p||g?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):m?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(sr,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:f,selectedOptions:h,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Mt,{className:"w-60",id:s.id,sortableType:a,column:s,children:k()})}function sr({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,l;return(l=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:l.find(u=>u.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function nr({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:l}=t.useEditorAside(),u={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:c,isFetching:h,isError:d,data:x}=t.useFilterQuery(u),j=x==null?void 0:x.records,{dateRange:p,setDateRange:g,initialDateRange:m}=t.useDateRangeFromRecords(j),{updateEditorFilterValue:v}=t.useEditorActions();function f(E){var C,b;const y={gte:(C=E==null?void 0:E.from)==null?void 0:C.toISOString(),lte:(b=E==null?void 0:E.to)==null?void 0:b.toISOString()};v(s.name,y)}function k(){v(s.name,null,!0),g(m)}function T(){return c||h?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):d?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):j?e.jsx(t.DateRangePopover,{title:u.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:p,setDateRange:g,onApply:f,onClear:k}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Mt,{className:"w-72",id:s.id,sortableType:a,column:s,children:T()})}function ar({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var g,m;const{setNodeRef:i,isOver:l,over:u}=t.useDroppable({id:s}),c=t.useDndStore(v=>v.activeId),h={},d=l||((m=(g=u==null?void 0:u.data)==null?void 0:g.current)==null?void 0:m.type)===o;function x(){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 j(v){const f=t.isDateDataType(v.type);return v.id===as.id?e.jsx(Mt,{id:v.id,sortableType:o,column:v,children:e.jsx(rr,{})},v.id):f?e.jsx(nr,{droppableId:s,sortableType:o,column:v},v.id):e.jsx(tr,{droppableId:s,sortableType:o,column:v},v.id)}const p=c?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",d&&"border border-muted-foreground/20"),ref:i,style:h,children:[e.jsx(t.Label,{className:"text-sm",children:a}),x(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:p==null?void 0:p.map(v=>j(v))})]})})}function rr(){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 or(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ar,{onRemoveColumn:r,sortableType:ct,id:lt,label:"Filters",columns:s,previewColumns:a})})}function ir(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);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(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(wn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(is,{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(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function lr(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(u=>u.isShowingVisual),r=t.useEditorStore(u=>u.showAIDialog),o=t.useEditorStore(u=>u.isDevMode);L.useEffect(()=>{var u,c,h,d;r?((u=s.current)==null||u.resize(0),(c=a.current)==null||c.resize(0)):((h=s.current)==null||h.resize(25),(d=a.current)==null||d.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ra,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx($a,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Le,{})})]}):e.jsx(Le,{})})]})}function l(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(er,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(ir,{}),e.jsx(or,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Le,{})})]})})]}):e.jsx(Le,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():l()})}function cr(s,a){const[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:l}=t.useSemaphorContext(),u=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.sql}),c=t.useEditorStore(_=>_.isDevMode),h=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.python}),{setCardPython:d,setCardSql:x,setRunSql:j,switchCardType:p,setQueryConfig:g}=t.useEditorActions(),m=t.useEditorStore(_=>_.currentAssitantScope)||[],v=t.useEditorStore(_=>_.userInputForAI),f=t.useEditorStore(_=>_.triggerAIRun),k=t.useEditorStore(_=>_.selectedDatabaseName),T=t.useEditorStore(_=>_.selectedTableName),E=t.useEditorStore(_=>_.selectedConnectionId),y=t.useEditorStore(_=>_.selectedSchemaName),C=t.useDashboardStore(_=>_.dashboard.aiScopeTables),{setTriggerAIRun:b,setCurrentAssitantScope:w}=t.useEditorActions(),{selectedDatamodelName:I,connectionType:D,selectedDatamodelId:S}=t.useEditorAside(),{messages:F,setMessages:O,reload:A,error:N,append:M,input:z,setInput:R,status:q,handleInputChange:B,handleSubmit:K,stop:J}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${l==null?void 0:l.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:c,aiContext:s},maxSteps:10,onError:_=>{console.log("on error",_)},onToolCall:$,onFinish(_,Q){U(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{f&&v&&(B({target:{value:v}}),setTimeout(()=>{K(),b(!1)},100))},[f,K,v,b,B]);async function $({toolCall:_}){if(["createChartFromSql","createForecast"].includes(_.toolName)){const Q=_.args.sql,se=_.args.python,ue=_.args.chartType;return p(ue),x(Q),d(se),j(!0),{status:"success",message:"Let the user know that chart is created"}}else if(_.toolName==="getTableColumns")r("Getting table columns...");else{if(_.toolName==="getUserSql")return u?{status:"success",sql:u,python:h||""}:{status:"error",message:"No SQL found"};if(_.toolName==="getCurrentTableScope")return r("Getting table scope..."),H(),{status:"success",tables:m};if(_.toolName==="generateQueryConfig"){r("Generating query config...");const Q=_.args.chartType,se=_.args.queryConfig;return p(Q),g(se),x(void 0),d(void 0),j(!0),{status:"success",queryConfig:se}}else r("Analyzing...")}}function U(_){i(Q=>Q?{promptTokens:Q.promptTokens+_.promptTokens,completionTokens:Q.completionTokens+_.completionTokens,totalTokens:Q.totalTokens+_.totalTokens}:_)}function G(_){const Q=t.removeFromScopeArray(m,_);V(Q)}function V(_){const Q=t.sanitizeAIScope(_);w(Q),O(se=>[...se,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function P(){const _={databaseName:k||"",schemaName:y||"",tableName:T||"",datamodelId:S||"",datamodelName:t.resolveDatamodelName(I),connectionId:E||"",connectionType:D||""},Q=t.dedup([...m,_]);V(Q)}function H(){const _={databaseName:k||"",schemaName:y||"",tableName:T||"",datamodelName:t.resolveDatamodelName(I),connectionId:E||"",connectionType:D||"",datamodelId:S||""};if(!t.isInAiScopeArray([...C||[],...m],_)||m.length===0){const se=t.dedup([...C||[],...m,_]).filter(ue=>ue.connectionId===_.connectionId);V(se)}}const Y=!["ready","error"].includes(q),Z=t.getErrorMessage(N);return{messages:F,setMessages:O,reload:A,append:M,input:z,setInput:R,isLoading:Y,handleSetAIScope:H,handleAddCurrentTableToScope:P,removeFromCurrentSelections:G,currentAssitantScope:m,setCurrentAssitantScope:w,handleInputChange:B,handleSubmit:K,stop:J,chatStatus:q,toolStatus:n,llmUsage:o,onFinish:a,errorMessage:Z}}const dr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Gt(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[l,u]=L.useState(!1),[c,h]=L.useState(!1),[d,x]=L.useState({selectedEntities:[]}),j=t.useDashboardStore(P=>P.dashboard.aiContext),p=t.useEditorStore(P=>P.card.dataSource),g=t.useEditorStore(P=>P.actions.setCardSql),m=t.useEditorStore(P=>P.actions.setRunSql),v=t.useEditorStore(P=>P.showAIDialog),f=t.useDashboardStore(P=>P.handleOpenAssistantProfile),{setShowAIDialog:k,setCardPython:T}=t.useEditorActions(),{setDataSource:E}=t.useEditorActions(),{assistantProfile:y}=t.useAssistantProfile(),{messages:C,setMessages:b,reload:w,append:I,input:D,setInput:S,isLoading:F,handleInputChange:O,handleSubmit:A,stop:N,chatStatus:M,llmUsage:z,errorMessage:R}=cr(d);t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:C}),L.useEffect(()=>{var P;v&&((P=a.current)==null||P.focus())},[v]);function q(P,H){H==="sql"?(g(P),m(!0)):H==="python"&&(T(P),m(!0))}function B(){var Y;const P=(Y=j==null?void 0:j.selectedEntities)==null?void 0:Y[0],H={connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"",mode:(P==null?void 0:P.type)==="dataset"?"semanticModel":"database",dbSelection:{database:(P==null?void 0:P.database)||"",schema:(P==null?void 0:P.schema)||"",entityType:(P==null?void 0:P.type)||"table"},selectedEntities:(j==null?void 0:j.selectedEntities)||[]};E(H),h(!0)}function K(){d.selectedEntities.length===0&&x({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function J(P){K();const H={role:"user",content:P.title+" "+P.subtitle};I(H)}function $(P){K(),I({role:"user",content:P})}function U(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function G(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const V=(D==null?void 0:D.length)===0&&(C==null?void 0:C.filter(P=>P.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:[G(),f&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(y==null?void 0:y.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",onClick:B,children:e.jsx(t.Settings,{className:"size-4"})}),U(),e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",onClick:()=>{b([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{k(!1)},children:e.jsx(En,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,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(t.PrintMessages,{messages:C,showTools:o,handleRun:q,showSystemMessage:l}),e.jsx(t.ChatStatus,{messages:C,chatStatus:M,errorMessage:R})]})}),e.jsxs("div",{className:"mb-3",children:[V&&!y&&e.jsx(t.Placeholders,{onClick:J,placeholders:dr}),e.jsx("div",{children:V&&y&&e.jsx(t.SeedQuestions,{seedQuestions:y.seedQuestions||[],handleSeedQuestionClick:$})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:S,stop:N,input:D,localAiContext:d,setLocalAiContext:x,handleInputChange:O,handleSubmit:P=>{K(),A(P)},isLoading:F,onFocus:()=>{}}),z&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",z.promptTokens," prompt tokens,"," ",z.completionTokens," completion tokens,"," ",z.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{open:c,onOpenChange:h,dataSource:p||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function ur(s){return s.flatMap(a=>a.columns.map(n=>({id:`${a.entityId}-${n.name}`,name:n.name,dataType:n.dataType,qualifiedEntityName:a.qualifiedEntityName,label:n.label||t.toTitleCase(n.name),description:n.description,entityId:a.entityId,entityName:a.entityName,entityType:a.entityType})))}function mr(s){if(s.type==="table"||s.type==="view"){if(s.database&&s.schema)return`${s.database}.${s.schema}.${s.name}`;if(s.database)return`${s.database}.${s.name}`}return s.name}function Te(s){var g;const a=t.useDashboardStore(m=>m.authToken)||s,{hasSchemaSupport:n}=t.useSelectedConnection(s),r=t.useEditorStore(m=>{var v;return(v=m.card.dataSource)==null?void 0:v.connectionId}),o=t.useEditorStore(m=>{var v,f;return(f=(v=m.card.dataSource)==null?void 0:v.selectedEntities)==null?void 0:f.filter(k=>k.type==="model")})||[],i=t.useEditorStore(m=>{var v,f;return(f=(v=m.card.dataSource)==null?void 0:v.selectedEntities)==null?void 0:f.filter(k=>k.type==="table"||k.type==="view")})||[];function l(m){return m.type==="model"?!!r&&!!m.id:m.type==="table"||m.type==="view"?n?!!r&&!!m.name&&!!m.database&&!!m.schema:!!r&&!!m.name&&!!m.database:!1}const u=[...o,...i],c=zs({queries:u.map(m=>({queryKey:["columns",r,m],queryFn:()=>t.getRequest("https://semaphor.cloud/api/v1/columns",(a==null?void 0:a.accessToken)||"",m.type==="model"?{connection_id:r,datamodel_id:m.id,database_name:"",schema_name:"",table_name:""}:{connection_id:r,datamodel_id:"",database_name:m.database,schema_name:m.schema,table_name:m.name}),enabled:!!r&&l(m)}))}),h=c.some(m=>m.isPending),d=c.some(m=>m.isError),x=(g=c.find(m=>m.isError))==null?void 0:g.error,j=c.map((m,v)=>{var T;const f=u[v],k=mr(f);return{entityId:f.id||f.name,entityType:f.type,entityName:f.name,label:f.label,description:f.description,qualifiedEntityName:k,columns:(T=m.data)==null?void 0:T.columns.map(E=>({id:`${f.name}-${E.column_name}`,name:E.column_name,dataType:E.data_type,label:E.label||t.toLabel(E.column_name),description:E.description||"",qualifiedEntityName:k,entityId:f.id||f.name,entityName:f.name,entityType:f.type}))}}).filter(m=>{var v;return((v=m==null?void 0:m.columns)==null?void 0:v.length)>0})||[],p=ur(j);return{columnGroups:j,columns:p,isLoading:h,hasError:d,error:x,refetch:()=>{c.forEach(m=>m.refetch())}}}function hr({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:l}=t.useSortable({id:s.id}),[u,c]=L.useState(!1),h={transform:t.CSS.Transform.toString(o),transition:i},d=t.getDataType(s.dataType),j=(p=>{const g=(p||"").toLowerCase();switch(t.getDataType(g)){case"number":return gt;case"date":return t.Calendar;case"boolean":return Xt;case"json":return sn;case"geo":return Nn;default:return Zt}})(s.dataType);return e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${l?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>c(!u),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(j,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",d==="string"?"text-blue-500":"",d==="number"?"text-green-500":"",d==="date"?"text-purple-500":"",d==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm dark:text-muted-foreground ${u?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:s.label||s.name}),s.label&&s.label!==s.name&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Name: ",s.name]}),e.jsx("p",{className:"text-xs text-gray-500",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type: ",s.dataType]})]})})]})}),e.jsx("button",{onClick:p=>{p.stopPropagation(),c(!u)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:u?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),u&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function xr({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(hr,{field:o},o.id))})})]})}function pr(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),l=t.useEditorStore(E=>E.card.dataSource),{columns:u=[],columnGroups:c=[],isLoading:h,error:d}=Te(),x=u.filter(E=>E.name.toLowerCase().includes(s.toLowerCase())||E.dataType.toLowerCase().includes(s.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),j=E=>E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency"?"metrics":"dimensions",g=(o==="all"?x:x.filter(E=>j(E)===o)).reduce((E,y)=>{const C=y.qualifiedEntityName||"Other Fields";return E[C]||(E[C]={label:t.toLabel(y.entityName),fields:[]}),E[C].fields.push(y),E},{});L.useEffect(()=>{const E=Object.keys(g);r(new Set(E))},[Object.keys(g).join(",")]);const m=E=>{const y=new Set(n);y.has(E)?y.delete(E):y.add(E),r(y)},v=x.filter(E=>j(E)==="dimensions").length,f=x.filter(E=>j(E)==="metrics").length,k=x.filter(E=>j(E)==="calculated").length,T=x.length>0;return h?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(ce,{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(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(t.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(t.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-[290px] grow flex-col gap-2 pb-6",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-2 p-1 pb-0",children:[u.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:E=>a(E.target.value)})}),T&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:E=>i(E),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(ut,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Ws,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),e.jsxs(t.ScrollArea,{className:"flex-1",children:[e.jsxs("div",{className:"space-y-2 p-1 pt-0",children:[Object.entries(g).map(([E,y])=>{const C=c.find(b=>b.entityName===E)||{entityName:E,label:y.label};return e.jsx(xr,{entityGroup:C,fields:y.fields,isOpen:n.has(E),onToggle:()=>m(E)},E)}),Object.keys(g).length===0&&u.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(g).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function fr(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(pr,{})," "]})}function gr({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),l=()=>{const C=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),i(new Set([...o,b.id]))},u=C=>{r({...n,joins:n.joins.filter(b=>b.id!==C)}),i(new Set([...o].filter(b=>b!==C)))},c=(C,b)=>{var S,F;const w=n.joins.find(O=>O.id===C);if(!w)return;const I={...w,...b},D=n.joins.map(O=>O.id===C?I:O);if((S=I.source)!=null&&S.name&&((F=I.target)!=null&&F.name)&&I.joinKeyGroups[0].keys.length===0){const O=a.find(z=>{var R;return z.name===((R=I.source)==null?void 0:R.name)}),A=a.find(z=>{var R;return z.name===((R=I.target)==null?void 0:R.name)}),N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="},M=[...I.joinKeyGroups];M[0]={...M[0],keys:[N]},I.joinKeyGroups=M,D[D.findIndex(z=>z.id===C)]=I}r({...n,joins:D})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:l,removeJoin:u,updateJoin:c,moveJoinUp:C=>{const b=n.joins.findIndex(w=>w.id===C);if(b>0){const w=[...n.joins],I={...w[b]},D={...w[b-1]};w[b]=D,w[b-1]=I,w.forEach((F,O)=>{F.sequence=O+1});const S={...n,joins:w};r(S)}},moveJoinDown:C=>{const b=n.joins.findIndex(w=>w.id===C);if(b<n.joins.length-1){const w=[...n.joins],I={...w[b]},D={...w[b+1]};w[b]=D,w[b+1]=I,w.forEach((F,O)=>{F.sequence=O+1});const S={...n,joins:w};r(S)}},toggleJoinExpansion:C=>{const b=new Set(o);b.has(C)?b.delete(C):b.add(C),i(b)},getAvailableSourceEntities:C=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(I=>I.id===C);if(b===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,b).forEach(I=>{w.add(I.source.name),w.add(I.target.name)}),a.filter(I=>w.has(I.name))},getAvailableTargetEntities:C=>a.filter(b=>b.name!==C),addJoinKeyGroup:C=>{const b=n.joins.find(I=>I.id===C);if(!b)return;const w=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];c(C,{joinKeyGroups:w})},updateGroupOperator:(C,b,w)=>{const I=n.joins.find(S=>S.id===C);if(!I)return;const D=[...I.joinKeyGroups];D[b]={...D[b],operator:w},c(C,{joinKeyGroups:D})},removeJoinKeyGroup:(C,b)=>{const w=n.joins.find(D=>D.id===C);if(!w)return;const I=[...w.joinKeyGroups];I.splice(b,1),c(C,{joinKeyGroups:I})},addJoinKey:(C,b)=>{const w=n.joins.find(O=>O.id===C);if(!w)return;const I=a.find(O=>O.name===w.source.name),D=a.find(O=>O.name===w.target.name),S=[...w.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${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"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="};S[b]={...S[b],keys:[...S[b].keys,F]},c(C,{joinKeyGroups:S})},updateJoinKey:(C,b,w,I,D)=>{const S=n.joins.find(M=>M.id===C);if(!S)return;const F=a.find(M=>M.name===S.source.name),O=a.find(M=>M.name===S.target.name),A=[...S.joinKeyGroups],N=A[b].keys[w];I==="sourceColumnName"&&F?A[b].keys[w]={...N,source:{...N.source,name:D}}:I==="targetColumnName"&&O?A[b].keys[w]={...N,target:{...N.target,name:D}}:I==="operator"&&(A[b].keys[w]={...N,operator:D}),c(C,{joinKeyGroups:A})},removeJoinKey:(C,b,w)=>{const I=n.joins.find(S=>S.id===C);if(!I)return;const D=[...I.joinKeyGroups];D[b].keys.splice(w,1),c(C,{joinKeyGroups:D})},generateSQLPreview:()=>{const C=[...n.joins].sort((I,D)=>I.sequence-D.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
403
+ `;k(B)}function z(){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(aa,{jsonString:JSON.stringify(h,null,2)})})}),h&&h.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(ft,{className:"size-3.5 text-muted-foreground"})})]})}function R(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.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(sa,{})}),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(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.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(na,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){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(t.Button,{title:"Shift + Enter",disabled:w||I,onClick:()=>{A()},className:"h-8 shrink-0",size:"sm",children:[w||I?e.jsx(ce,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(is,{sql:b==null?void 0:b.sql,error:N,onClick:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:B=>n(B),className:"",size:"sm",children:e.jsx(ta,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:l,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:l?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}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:[R(),z()]}),q()]})}function oa({data:s}){var l;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(u=>({accessorKey:u,header:({column:c})=>{const h=c.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>c.toggleSorting(c.getIsSorted()==="asc"),children:[u,h==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):h==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(u=>e.jsx(t.TableRow,{className:"",children:u.headers.map(c=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:c.isPlaceholder?null:t.flexRender(c.column.columnDef.header,c.getContext())},c.id))},u.id))}),e.jsx(t.TableBody,{children:(l=i.getRowModel().rows)!=null&&l.length?i.getRowModel().rows.map(u=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":u.getIsSelected()&&"selected",children:u.getVisibleCells().map(c=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(c.column.columnDef.cell,c.getContext())},c.id))},u.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ia({card:s}){var k,T,E,y,C,b,w,I,D,S,F;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),l=t.getTokenParams(i==null?void 0:i.accessToken),u=t.useDashboardStore(O=>O.themeStyle),c={colors:((T=(k=u==null?void 0:u.chart)==null?void 0:k.dataset)==null?void 0:T.backgroundColor)||[]};(E=s.customCardPreferences)!=null&&E.inputData;const{getCard:h}=t.useCustomVisual(((y=s.customCardPreferences)==null?void 0:y.url)||""),d=((C=s.customCardPreferences)==null?void 0:C.visualType)||"single",x=t.useEditorStore(O=>O.frame),{setCustomCardPreferences:g}=t.useEditorActions(),{data:p}=t.useDashboardCardQuery(s),j=L.useCallback((O,A)=>{o(N=>({...N,[O]:A}))},[]);if(!((b=s.customCardPreferences)!=null&&b.componentName))return null;const m=h((w=s.customCardPreferences)==null?void 0:w.componentName);function v(O){n(O)}const f=Object.keys(((I=s.customCardPreferences)==null?void 0:I.dataInputCardIds)||{}).map(O=>{var M,z,R;const A=(z=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:z[O].cardId,N=(R=x==null?void 0:x.cards)==null?void 0:R.find(q=>q.id===A);return N||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[m&&d==="single"&&e.jsx(m,{params:l,theme:c,settings:(D=s.customCardPreferences)==null?void 0:D.settings,onDataChange:j,data:(p==null?void 0:p.records)||[]}),m&&d==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=s.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(O=>{var M,z,R;const A=(z=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:z[O].cardId,N=(R=x==null?void 0:x.cards)==null?void 0:R.find(q=>q.id===A);if(N)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:v,onDataChange:j,dataInputIndex:O,card:N},N.id+O)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(m,{theme:c,onDataChange:j,settings:f.map(O=>{var A;return(A=O==null?void 0:O.customCardPreferences)==null?void 0:A.settings}),data:f.map(O=>O!=null&&O.id?r==null?void 0:r[O.id]:[])})})]})]},(F=s.customCardPreferences)==null?void 0:F.componentName)})}function us({className:s,...a}){var v;const n=t.useEditorStore(f=>f.card),r=((v=n.customCardPreferences)==null?void 0:v.showCardHeader)??!0,o=t.useEditorStore(f=>f.frame),i=t.useDashboardStore(f=>f.dashboard.filters);t.useEditorStore(f=>f.actions.setRunSql);const{updateFilter:l}=t.useDashboardActions(),u=i==null?void 0:i.find(f=>f.id===o.filterId),{data:c,isLoading:h,isFetching:d}=t.useDashboardCardQuery(n),{setCard:x}=t.useEditorActions(),{data:g}=t.useTopoJson(n),p=L.useMemo(()=>!n.id||!(c!=null&&c.records)?null:t.createChartConfig({card:n,data:c==null?void 0:c.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:g}),[n.id,c==null?void 0:c.records,n.type,n.queryConfig,n.customCfg,n.preferences,g]);function j(f){return e.jsx(ia,{card:f})}function m(){if(c!=null&&c.records&&(c==null?void 0:c.records.length)===0&&!h&&!d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No records to display"})]});if(!n.id)return null;if(n.type==="custom")return j(n);if(!["table","custom"].includes(n.type)&&p)return e.jsx(e.Fragment,{children:h||d?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:p})});if(n.type==="table"&&(c!=null&&c.records)&&(c==null?void 0:c.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(t.TableVisual,{card:n,data:c==null?void 0:c.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:f=>x({...n,title:f}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:f=>x({...n,description:f}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:u.title||u.column,onSave:f=>l({...u,title:f}),children:e.jsx(t.Label,{children:u.title})}),e.jsx(t.FilterComponent,{filter:u})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:m()})]})}const Xe=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.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:s,value:a,onChange:n}),la=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.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."})]})]}),ca=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Xe,{language:"javascript",value:s,onChange:o})})]}),da=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function ua(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[l,u]=L.useState(""),[c,h]=L.useState(""),d=t.useEditorStore(y=>y.card),x=t.useEditorStore(y=>y.card.customCfg),g=x?JSON.stringify(x,null,2):"",{data:p}=t.useDashboardCardQuery(d),{data:j}=t.useTopoJson(d),{setCardCustomCfg:m,setCustomVisualCode:v}=t.useEditorActions(),f=y=>{var C,b;return JSON.stringify({...y,data:{...y.data,datasets:(b=(C=y.data)==null?void 0:C.datasets)==null?void 0:b.map(w=>({...w,data:[]}))}},null,2)},k=()=>{var C,b;if(!((C=p==null?void 0:p.records)!=null&&C.length))return;const y=t.createChartConfig({card:d,data:p.records,cardType:d.type,queryConfig:d.queryConfig,preferences:d.preferences,topoJson:j});if(y){r(f(y)),u(((b=d.preferences)==null?void 0:b.customVisualCode)||"");const w=t.merge(y,x);i(f(w))}},T=()=>{try{if(l&&v(l),o){const y=JSON.parse(o),C=t.getObjectDiff(JSON.parse(n),y);m(C),h("")}}catch{h("Invalid JSON configuration")}},E=Object.keys(x||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:k,className:E?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(la,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(us,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ca,{customCode:l,cardCustomCfgString:g,mergedConfig:o,onConfigChange:y=>i(y??""),onCodeChange:y=>u(y??"")})]}),e.jsx(da,{error:c,hasCardCustomConfig:!!x,onReset:()=>{i(n),m(null)},onApply:T,onClose:()=>a(!1)})]})]})}function ms(s){const[a,n]=L.useState(null);return a}function hs(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function ma({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:l}=t.useEditorActions(),{data:u}=hs();function c(h,d){r(null),o({}),i(h),d&&l({type:"component",visualType:"single",url:d.url,componentName:d.name,icon:d.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var d;if(u){const g=(await Promise.all((d=u==null?void 0:u.plugins)==null?void 0:d.map(async p=>(await t.loadManifest(p.value)).visuals.map(v=>({name:v.name,icon:v.icon,url:p.value}))))).flat();n(g)}})()},[u]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((h,d)=>e.jsx(ha,{text:h.name,onClick:()=>c("custom",h),icon:h.icon},h.url+h.name+d))})]})}const ha=({text:s,icon:a,onClick:n})=>{const r=ms(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function wt(s){return ye({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:[]}]})(s)}function xa(s){return ye({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:[]}]})(s)}function kt(s){return ye({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:[]}]})(s)}function Et(s){return ye({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:[]}]})(s)}function It(s){return ye({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:[]}]})(s)}function Dt(s){return ye({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:[]}]})(s)}function xs({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(d=>d.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(d,x){i(null),r({}),n(d),["kpi","custom","text","map"].includes(d)&&(o(!0),u(void 0)),s==null||s()}const h=1e3;return e.jsxs("div",{className:"grid grid-cols-4 place-items-center",children:[e.jsx(t.IconButton,{openDelay:h,tooltip:"Table",onClick:()=>c("table"),className:"h-10 p-4",children:e.jsx(He,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bar Chart",onClick:()=>c("bar"),className:"h-10 p-4",children:e.jsx(Ge,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Line Chart",onClick:()=>c("line"),className:"h-10 p-4",children:e.jsx($e,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Bar Chart",onClick:()=>c("stackedBar"),className:"h-10 p-4",children:e.jsx(dt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Line Chart",onClick:()=>c("stackedLine"),className:"h-10 p-4",children:e.jsx(It,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Scatter Chart",onClick:()=>c("scatter"),className:"h-10 p-4",children:e.jsx(xt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bubble Chart",onClick:()=>c("bubble"),className:"h-10 p-4",children:e.jsx(kt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Pie Chart",onClick:()=>c("pie"),className:"h-10 p-4",children:e.jsx(ht,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Doughnut Chart",onClick:()=>c("doughnut"),className:"h-10 p-4",children:e.jsx(pt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Funnel Chart",onClick:()=>c("funnel"),className:"h-10 p-4",children:e.jsx(Et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Radar Chart",onClick:()=>c("radar"),className:"h-10 p-4",children:e.jsx(yt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Polar Area Chart",onClick:()=>c("polarArea"),className:"h-10 p-4",children:e.jsx(wt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Tornado Chart",onClick:()=>c("tornado"),className:"h-10 p-4",children:e.jsx(vt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>c("range"),className:"h-10 p-4",children:e.jsx(mt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"KPI",onClick:()=>c("kpi"),className:"h-10 p-4",children:e.jsx(Dt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Text",onClick:()=>c("text"),className:"h-10 p-4",children:e.jsx(Jt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>c("map"),className:"h-10 p-4",children:e.jsx(jt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Custom",onClick:()=>c("custom"),className:"h-10 p-4",children:e.jsx(bt,{className:t.cn("size-5",a)})})]})}function pa({chartType:s,className:a,customIcon:n,componentName:r}){const o=ms();switch(s){case"bar":return e.jsx(Ge,{className:a});case"line":return e.jsx($e,{className:a});case"pie":return e.jsx(ht,{className:a});case"radar":return e.jsx(yt,{className:a});case"scatter":return e.jsx(xt,{className:a});case"bubble":return e.jsx(kt,{className:a});case"doughnut":return e.jsx(pt,{className:a});case"stackedBar":return e.jsx(dt,{className:a});case"stackedLine":return e.jsx(It,{className:a});case"polarArea":return e.jsx(wt,{className:a});case"funnel":return e.jsx(Et,{className:a});case"tornado":case"pyramid":return e.jsx(vt,{className:a});case"range":return e.jsx(mt,{className:a});case"kpi":return e.jsx(Dt,{className:a});case"text":return e.jsx(Zt,{className:a});case"map":return e.jsx(jt,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(bt,{className:a});default:return e.jsx(He,{className:a})}}function fa({variant:s="ghost"}){var i,l;const[a,n]=L.useState(!1),r=t.useEditorStore(u=>u.card),o=r.type;return t.useDashboardStore(u=>u.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(pa,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(l=r.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:u=>u.preventDefault(),className:"w-50",children:[e.jsx(xs,{onChartTypeChange:()=>n(!1)}),e.jsx(ma,{onChartTypeChange:()=>n(!1)})]})]})}const Ae="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function _t(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ga(){var M,z,R,q,B,K;const[s,a]=L.useState(!1),n=t.useEditorStore(J=>{var $;return($=J.card)==null?void 0:$.preferences}),r=t.useEditorStore(J=>{var $;return($=J.card)==null?void 0:$.type}),o=t.getNumberAxis(n,{}),[i,l]=L.useState(_t(n,r)),[u,c]=L.useState(((R=(z=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:z[o])==null?void 0:R.min)||""),[h,d]=L.useState(((K=(B=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:B[o])==null?void 0:K.max)||""),[x,g]=L.useState(u||h?"custom":"auto"),[p,j]=L.useState(""),[m,v]=L.useState(0),[f,k]=L.useState(""),[T,E]=L.useState(""),[y,C]=L.useState(""),b=t.useEditorStore(J=>J.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),I=t.useEditorStore(J=>J.card),D=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var J,$,Y,_,V,P,H,U,Z,de,G,Q,se,me;l(_t(n,r)),c(((Y=($=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:$[o])==null?void 0:Y.min)===0?0:""),d(((P=(V=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:V[o])==null?void 0:P.max)||""),j(((de=(Z=(U=(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales)==null?void 0:U[o])==null?void 0:Z.ticks)==null?void 0:de.stepSize)||""),v(((G=n==null?void 0:n.numberAxisFormat)==null?void 0:G.decimalPlaces)||0),k(((Q=n==null?void 0:n.numberAxisFormat)==null?void 0:Q.suffix)||""),E(((se=n==null?void 0:n.numberAxisFormat)==null?void 0:se.currency)||""),C(((me=n==null?void 0:n.numberAxisFormat)==null?void 0:me.locale)||"")},[s,n,o,r]);function S(J,$){return $===""||/^[0-9\b]+$/.test($)?Number($):Number(J)}function F(){const J=[...new Set(t.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(t.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(t.Select,{value:T||"none",onValueChange:$=>E($==="none"?"":$),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),J.map($=>e.jsx(t.SelectItem,{value:$,children:$},$))]})})]}),e.jsxs(t.Select,{value:y,onValueChange:$=>C($),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map($=>e.jsx(t.SelectItem,{value:$.locale,children:$.locale},$.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:m,onChange:$=>v(Number($.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ae}`})]})]})}function O(){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(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:D,value:i,onValueChange:J=>l(J),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:D,id:"scale-option",value:x,onValueChange:J=>g(J),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.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(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),x==="custom"&&i=="linear"&&A()]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:u,onChange:J=>c($=>S($,J.target.value)),className:`col-span-1 h-8 w-full ${Ae}`}),e.jsx(t.Input,{value:h,onChange:J=>d($=>S($,J.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ae}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:p,onChange:J=>j($=>S($,J.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ae}`})]})]})}function N(){var _;let J={};x==="custom"&&(J={min:u,max:h,ticks:{stepSize:p}});const $={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales,[o]:{type:i,...i==="linear"?J:{}}}},numberAxisFormat:{decimalPlaces:m,suffix:f,currency:T,locale:y}};console.log($),b($);const Y={...I,preferences:$};w(Y)}return e.jsxs(t.Popover,{onOpenChange:J=>a(J),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(on,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",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:[F(),O(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:N,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function ja(){const s=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.position}),a=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.align}),n=t.useEditorStore(u=>{var c,h,d,x;return(x=(d=(h=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:h.plugins)==null?void 0:d.legend)==null?void 0:x.display}),{setLegendOptions:r}=t.useEditorActions(),o=u=>{r({display:u,position:s,align:a})},i=u=>{r({display:n,position:u,align:a})},l=u=>{r({display:n,position:s,align:u})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(gn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"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(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.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(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(_e,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Gs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(qe,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx($s,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>l("start"),children:e.jsx(Rs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>l("center"),children:e.jsx(Bs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>l("end"),children:e.jsx(Ps,{className:"size-4"})})]})]})]})]})]})})]})}function ya(){const s=t.useEditorStore(i=>{var l,u;return(u=(l=i.card.preferences)==null?void 0:l.chartOptions)==null?void 0:u.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(Bt,{className:"size-4"}):e.jsx(zt,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Bt,{className:"size-4"}):e.jsx(zt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function ps(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>l.isShowingVisual),n=t.useEditorStore(l=>{var u,c;return(c=(u=l.card)==null?void 0:u.preferences)==null?void 0:c.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const l=["xy","none","x","y"],c=(l.indexOf(r)+1)%l.length;o(l[c])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(ya,{}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ga,{}),e.jsx(ja,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(xn,{className:"size-4"}),r==="x"&&e.jsx(nn,{className:"size-4"}),r==="y"&&e.jsx(Dn,{className:"size-4"}),r==="none"&&e.jsx(An,{className:"size-4"})]})]}):null}function ba(){const s=t.useEditorStore(j=>j.frame),a=t.useEditorStore(j=>j.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),l=(j,m)=>{j.dataTransfer.setData("tabIndex",m.toString())},u=j=>{j.preventDefault()},c=(j,m)=>{const v=j.dataTransfer.getData("tabIndex");if(v===m.toString())return;const f=Array.from(s.cards),[k]=f.splice(parseInt(v),1);f.splice(m,0,k),n({...s,cards:f})};function h(j){const m=s.cards.filter(k=>k.id!==j),v=m[0],f={...s,cards:m,activeCardId:v.id};n(f),r(v.id),o(v)}function d(j,m){const v={...s,cards:[...s.cards,m],activeCardId:j.id};n(v),r(m.id)}function x(){const j={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};d(a,j)}function g(j){const m={connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};d(j,m)}function p(j,m){return j.cards.length===1&&(m.displayTab===!0||m.displayTab===void 0)||j.activeCardId!==m.id&&(m.displayTab===!0||m.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=m.displayTab===void 0?!1:!m.displayTab;o({...m,displayTab:v}),i({...m,displayTab:v})},children:m.displayTab===!0||m.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ln,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((j,m)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:v=>l(v,m),onDragOver:u,onDrop:v=>c(v,m),className:"",value:j.id,children:[p(s,j),e.jsx(t.Editable,{enabled:s.activeCardId===j.id,text:j.tabTitle||j.title,onSave:v=>{o({...a,tabTitle:v}),i({...a,tabTitle:v})},children:j.tabTitle||j.title},j.id),s.activeCardId===j.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>h(j.id)})]},j.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>g(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:x,children:e.jsx(rn,{className:"h-4 w-4"})})]})})}function fs(){const s=t.useEditorStore(m=>m.frame),a=t.useEditorStore(m=>m.card),n=t.useEditorStore(m=>m.isSqlRunning),r=t.useEditorStore(m=>m.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:l,setIsDevMode:u,setRunSql:c}=t.useEditorActions(),{data:h,isLoading:d,isFetching:x}=t.useDashboardCardQuery(a);function g(m){const v=s.cards.find(f=>f.id===m);if(v!=null&&v.sql){r||u(!0),i(m);return}if(v!=null&&v.queryConfig){r&&u(!1),p(m),i(m);return}r||p(m),i(m)}function p(m){const v={...s,cards:s.cards.map(k=>k.id===a.id?a:k),activeCardId:m};o(v);const f=v.cards.find(k=>k.id===m);f.sql&&c(!0),l(f)}function j(){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(t.KPICard,{card:a,data:h==null?void 0:h.records,isPending:d})})}):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(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:h==null?void 0:h.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(us,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:g,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(m=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:m.id,children:j()},m.id)),e.jsx(ba,{})]})}function Le({children:s}){var k;t.useEditorStore(T=>T.frame);const a=t.useEditorStore(T=>T.card),n=t.useEditorStore(T=>T.isDevMode),r=t.useEditorStore(T=>T.isShowingVisual),o=t.useDashboardStore(T=>T.isVisualEditing),i=t.useEditorStore(T=>T.pythonStdOut);t.useEditorStore(T=>T.actions.setRunSql);const{setFrame:l,setCard:u,setActiveTabCardId:c,runAssistant:h,setIsDevMode:d}=t.useEditorActions(),{data:x,isLoading:g,isFetching:p,error:j}=t.useDashboardCardQuery(a);function m(){const T=JSON.stringify(x==null?void 0:x.records,null,2),E=new Blob([T],{type:"application/json"}),y=URL.createObjectURL(E),C=document.createElement("a");C.href=y,C.download=`${a.title}.json`,C.click()}function v(){const E=[Object.keys(x==null?void 0:x.records.reduce((w,I)=>({...w,...I}),{})).join(","),...((x==null?void 0:x.records)||[]).map(w=>Object.values(w).join(","))].join(`
404
+ `),y=new Blob([E],{type:"text/csv"}),C=URL.createObjectURL(y),b=document.createElement("a");b.href=C,b.download=`${a.title}.csv`,b.click()}function f(){const T=`Can you get the documentation for ${a.type} chart?`;h(T)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(g||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(ce,{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(fa,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:f,children:e.jsx(Ys,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(ua,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.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(xa,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:m,children:e.jsx(dn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(x==null?void 0:x.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:[s,e.jsx(ps,{})]}),n&&e.jsx(Ca,{})]}),r?e.jsx(fs,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(va,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(oa,{data:(x==null?void 0:x.records)||[]}),(j||(x==null?void 0:x.error))&&e.jsx("span",{className:"font-mono text-xs",children:(j==null?void 0:j.message)||((k=x==null?void 0:x.error)==null?void 0:k.message)})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function va(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.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(t.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(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ca(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Na(){var m,v;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=hs(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),o=t.useEditorStore(f=>f.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:l}=t.useEditorActions(),{components:u,manifest:c}=t.useCustomVisual((s==null?void 0:s.url)||""),h=(m=c==null?void 0:c.visuals)==null?void 0:m.find(f=>f.name===(s==null?void 0:s.componentName));function d(f,k){if(!s)return;const E={...(s==null?void 0:s.dataInputCardIds)||{},[f]:{cardId:k,hookRef:null}};l({...s,dataInputCardIds:E})}function x(f){var T,E;const k=(T=o==null?void 0:o.cards)==null?void 0:T.filter(y=>{var C;return((C=y==null?void 0:y.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(y=>({value:y.id,label:y.tabTitle||y.title}));return e.jsx("div",{className:"space-y-2",children:(E=f==null?void 0:f.dataInputs)==null?void 0:E.map((y,C)=>{var b,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:y}),e.jsx(le,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((w=(b=s==null?void 0:s.dataInputCardIds)==null?void 0:b[C])==null?void 0:w.cardId)||"",onValueChange:I=>d(C,I)})]},C+Math.random())})})}function g(f,k,T=[],E=""){var y,C;return s?f==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((y=s==null?void 0:s.settings)==null?void 0:y[k])||E,onChange:b=>{l({...s,settings:{...s==null?void 0:s.settings,[k]:b.target.value}})}},k):f==="select"?e.jsx(le,{className:"h-8 w-full",label:"",options:T,value:((C=s==null?void 0:s.settings)==null?void 0:C[k])||E,onValueChange:b=>{l({...s,settings:{...s==null?void 0:s.settings,[k]:b}})}}):null:null}function p(f){const k=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([T,E])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:E.title}),g(E.ui,T,E.options,E.defaultValue)]},T))})}function j(f){s&&l({...s,visualType:f,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.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(le,{icon:e.jsx(Us,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:f=>l({...s||{url:"",componentName:""},url:f})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:j,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:u&&e.jsx(le,{icon:e.jsx(an,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.filter(f=>f.type===i).map(f=>({value:f.name,label:f.name})))||[],value:s.componentName,onValueChange:f=>{console.log("changing value",f),l({...s,componentName:f})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[h&&h.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:x(h)})]}),h&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(h)})})]})]})]})}function be(){const[s,a]=L.useState([]),n=t.useEditorStore(h=>h.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(h=>h.actions),i=t.useEditorStore(h=>h.queryResultColumns);t.useEditorStore(h=>{var d;return(d=h.card.preferences)==null?void 0:d.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(h,d){var x,g;d?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:h,expression:""}]}):o({...n,onClickFilter:[{columnIndex:h,expression:""}]}):(o({...n,onClickFilter:(g=n==null?void 0:n.onClickFilter)==null?void 0:g.filter(p=>p.columnIndex!==h)}),a(p=>{const j=[...p];return j[h]=!1,j}))}function u(h,d){var g;const x=(g=n==null?void 0:n.onClickFilter)==null?void 0:g.map(p=>p.columnIndex===h?{...p,expression:d.target.value}:p);o({...n,onClickFilter:x})}function c(h){var d,x,g,p;if(s!=null&&s[h]||(x=(d=n==null?void 0:n.onClickFilter)==null?void 0:d.find(j=>j.columnIndex===h))!=null&&x.expression)return e.jsx(t.Input,{value:(p=(g=n==null?void 0:n.onClickFilter)==null?void 0:g.find(j=>j.columnIndex===h))==null?void 0:p.expression,onChange:j=>u(h,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((h,d)=>{var x,g;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(t.Checkbox,{checked:!!((x=n==null?void 0:n.onClickFilter)!=null&&x.find(p=>p.columnIndex===d)),onCheckedChange:p=>l(d,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:h}),e.jsx("div",{className:"flex items-center gap-2",children:((g=n==null?void 0:n.onClickFilter)==null?void 0:g.find(p=>p.columnIndex===d))&&e.jsx(t.Pencil,{onClick:()=>{a(p=>{const j=[...p];return j[d]=!p[d],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),c(d)]})},h)})]})}function Sa({idx:s}){var u;const a=t.useEditorStore(c=>{var h;return(h=c.card)==null?void 0:h.preferences}),n=t.useEditorStore(c=>{var h;return(h=c.card.preferences)==null?void 0:h.datasetOptions}),r=t.useEditorStore(c=>c.actions.setCardPreferences),o=(u=a==null?void 0:a.chartOptions)==null?void 0:u.indexAxis,i=n==null?void 0:n.find(c=>c.idx===s);function l(c,h){(c==="end"||c==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const d={display:c!=="none",align:c,anchor:c,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:h,datalabels:d}]});else{const x={...i};x.datalabels=d;const g=n==null?void 0:n.map(p=>p.idx===h?x:p);r({...a,datasetOptions:g})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Wt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(jn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(bn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function gs(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);o=l.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ve({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function js(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var h,d,x;return(x=(d=(h=c==null?void 0:c.card)==null?void 0:h.preferences)==null?void 0:d.chartOptions)==null?void 0:x.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:l,keys:u}=gs();return u.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(c=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:c,children:ys(c)},c))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:l.map((c,h)=>e.jsx(bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:c,idx:h},c))})]})]})}function ys(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function bs({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(d=>{var x;return(x=d.card)==null?void 0:x.preferences}),l=t.useEditorStore(d=>{var x,g;return(g=(x=d.card)==null?void 0:x.preferences)==null?void 0:g.datasetOptions}),u=l==null?void 0:l.find(d=>d.idx===a),{setCardPreferences:c}=t.useEditorStore(d=>d.actions);function h(d){if(!u)c({...i,datasetOptions:[...l||[],{idx:a,type:d==="area"?"line":d,fill:d==="area"?"origin":""}]});else{const x={...u};x.type=d==="area"?"line":d,x.fill=d==="area"?"origin":"";const g=l==null?void 0:l.map(p=>p.idx===a?x:p);c({...i,datasetOptions:g})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Ve,{className:"max-w-[100px]",title:s,children:ys(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ge,{onClick:()=>h("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx($e,{onClick:()=>h("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Xs,{onClick:()=>h("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Sa,{idx:a})]})]})}function vs(){const s=t.useEditorStore(p=>p.selectedConnectionId),a=t.useEditorStore(p=>p.selectedDatamodelId),n=t.useEditorStore(p=>p.selectedDatabaseName),r=t.useEditorStore(p=>p.selectedSchemaName),o=t.useEditorStore(p=>p.selectedTableName),i=t.useDashboardStore(p=>p.dashboard.filters)||[],l=t.useDashboardStore(p=>p.actions.addFilter),u=t.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:c}=t.useDashboardActions(),{modelItems:h,tableName:d,connectionType:x}=t.useEditorAside();function g(p,j="dashboard"){var b;const m=t.fmt(p.column_name),v=t.fmt(n||""),f=t.fmt(r||""),k=t.fmt(d);let T=t.getQualifiedTableName({schemaName:f,tableName:k,connectionType:x,databaseName:v}),E=`${T}.${m}`;const y=(b=h==null?void 0:h.find(w=>w.id===a))==null?void 0:b.name;a&&a!=="none"&&(E=`${t.DATAMODEL_NAMESPCACE}.${y}.${m}`,T=`${t.DATAMODEL_NAMESPCACE}.${y}`);const C=i==null?void 0:i.find(w=>w.column===E&&w.table===k&&(w.database===v||w.database===n));if(C)c(C.id),u(C.id);else{const w=t.v4();return d==="api"&&s?(l({location:j,id:w,column:E,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(p.data_type,T,m)}),w):(l({id:w,location:j,column:E,title:p.column_name,dataType:p.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(p.data_type,T,m)}),w)}}return{assignFilter:g}}function we(){const s=t.useDashboardStore(u=>u.dashboard.filters),a=t.useEditorStore(u=>u.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=vs();function i(u){const c=o(u,"frame");n({...a,filterId:c})}const l=s==null?void 0:s.find(u=>u.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(wa,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function wa({columns:s,onSelect:a}){var l;const[n,r]=re.useState(!1),[o,i]=re.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(l=s.find(u=>u.column_name===o))==null?void 0:l.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(u=>e.jsxs(t.CommandItem,{value:u.column_name,onSelect:c=>{const h=c===o?"":c;i(h),r(!1),h&&a(u)},children:[u.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===u.column_name?"opacity-100":"opacity-0")})]},u.column_name))})]})]})})]})}function ka({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(js,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(be,{}),e.jsx(we,{})]})]})]})})}function Tt(){var o,i,l;const s=t.useEditorStore(u=>u.card.type),a=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:n}=t.useEditorStore(u=>u.actions);function r(u){var d;const c={datalabels:{display:u!=="none",align:u,anchor:u,clamp:!0}},h={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins,...c}}};n(h),console.log(u)}return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((l=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.datalabels)==null?void 0:l.anchor)||"none",onValueChange:r,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function Ea({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Tt,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(be,{}),e.jsx(we,{})]})]})]})})}const Ia={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Da={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Ta(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:Ma(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Tt,{}),e.jsx(be,{}),e.jsx(we,{})]})]})}function Ma(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.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(Ia,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.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(Da,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.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(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.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(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.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 Aa(){var c,h,d,x,g;const s=t.useEditorStore(p=>p.card.preferences),a=t.useEditorStore(p=>p.actions.setCardPreferences),n=t.useEditorStore(p=>p.actions.setNumberFormat);t.useEditorStore(p=>{var j,m;return(m=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:m.decimalPlaces});const r=t.useEditorStore(p=>{var j,m;return(m=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:m.locale}),o=t.useEditorStore(p=>{var j,m;return(m=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:m.currency});t.useEditorStore(p=>p.actions.setFilterOnClickField);const i=t.useEditorStore(p=>{var j,m;return(m=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:m.colorRanges})||[],l=t.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((c=s==null?void 0:s.formatNumber)!=null&&c.enabled),onCheckedChange:p=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:p}})}}),e.jsx(t.Label,{children:"Format Number"})]}),((h=s==null?void 0:s.formatNumber)==null?void 0:h.enabled)===!0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:r||"none",onValueChange:p=>{var j,m,v;return n(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((m=s==null?void 0:s.formatNumber)==null?void 0:m.currency)||"",p,((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),t.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(t.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:p=>{var j,m,v;console.log("currency",p),n(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((m=s==null?void 0:s.formatNumber)==null?void 0:m.locale)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(t.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((x=(d=s==null?void 0:s.formatNumber)==null?void 0:d.decimalPlaces)==null?void 0:x.toString())||"0",onValueChange:p=>{var j,m,v;return n(Number(p),((j=s==null?void 0:s.formatNumber)==null?void 0:j.currency)||"",((m=s==null?void 0:s.formatNumber)==null?void 0:m.locale)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(t.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,m,v;return n(((j=s==null?void 0:s.formatNumber)==null?void 0:j.decimalPlaces)||0,((m=s==null?void 0:s.formatNumber)==null?void 0:m.currency)||"",((v=s==null?void 0:s.formatNumber)==null?void 0:v.locale)||"",p.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(t.ColorFormat,{colorRanges:i,setColorRanges:l})]})]})}function La(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.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:s=>s.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(Aa,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ze({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.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(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const Oa=[{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"}],Fa=["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"],za=Fa.map(s=>({label:s,value:s}));function Ba(){var c,h,d,x,g,p,j,m,v,f,k,T,E,y,C,b,w,I;const s=t.useEditorStore(D=>D.card),a=(h=(c=s==null?void 0:s.preferences)==null?void 0:c.mapVisualOptions)==null?void 0:h.topoJsonUrl,[n,r]=L.useState(((x=(d=s==null?void 0:s.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(D=>({label:D,value:D}))||[],u=[{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(Ze,{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(t.Separator,{className:"my-4"}),e.jsx(Ze,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(le,{className:"h-9",options:u,onValueChange:D=>{console.log("value",D),o({...s.preferences,mapVisualOptions:{topoJsonUrl:D}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:D=>{r(D.target.value)},onBlur:()=>{var D;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(D=s.preferences)==null?void 0:D.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(le,{className:"h-9",options:l,value:((p=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,objectKey:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(le,{className:"h-9",options:Oa,value:((m=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:m.projection)||"",label:"Projection",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projection:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(le,{className:"h-9",options:za,value:((f=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,colorScale:D}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Ze,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((T=(k=s.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:D=>{var S;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(D.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((C=(y=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:C[0])||0,onChange:D=>{var S,F,O,A;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(D.target.value),((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(w=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:I[1])||0,onChange:D=>{var S,F,O,A;o({...s.preferences,mapVisualOptions:{...(S=s.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[0])||0,Number(D.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(be,{})]})}function Ra(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.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(t.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(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Tt,{}),s==="text"&&e.jsx(Ra,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(be,{}),e.jsx(we,{})]})]})]})})}function Pa(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(le,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.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(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(js,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(be,{}),e.jsx(we,{})]})]})]})})}function Va({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.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(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(be,{}),e.jsx(we,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.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 qa=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:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),_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 y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ga=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:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function $a(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Pa,{});case"tornado":case"pyramid":return e.jsx(Oe,{docContent:qa,cardType:n});case"kpi":return e.jsx(La,{});case"line":case"bar":return e.jsx(ka,{cardType:n});case"range":return e.jsx(Oe,{docContent:_a,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Oe,{cardType:n});case"bubble":case"scatter":return e.jsx(Ea,{cardType:n});case"table":return e.jsx(Va,{cardType:n});case"text":return e.jsx(Oe,{docContent:Ga,cardType:n,suffix:"Visual"});case"map":return e.jsx(Ba,{});case"custom":return e.jsx(Na,{});default:return e.jsx(Ta,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Cs({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(l=>l.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(l=>l.value===a.granularity)||n[0]);function i(l){r(l)}return e.jsx(le,{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:l=>i(l),label:s,showPlaceholderLabel:!1})}const Ha=[{label:"Sum",value:"SUM",logo:e.jsx(Qt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(gt,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(mn,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(_s,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(qe,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(_e,{className:"size-3.5"})}];function Ja({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ha;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:Ee(s.name,o)};a(s.id,i)}return e.jsx(Cs,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Ua=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Ya({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:Se(s.name,r)};a(s.id,o)}return e.jsx(Cs,{column:s,functions:Ua,onFunctionChange:r=>n(r),label:"Granularity"})}function Ka({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let u=[];(n===fe||n===ge||n===je)&&(u=r);const c=u==null?void 0:u.filter(h=>h.column_name!==s.name);return c==null?void 0:c.map(h=>({id:h.column_name,value:h.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function l(u){const c=r==null?void 0:r.find(h=>{var d;return h.column_name===((d=u[0])==null?void 0:d.id)});c&&a(c)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:l,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:s.name})}function Qa({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions(),{transformedMetricKeys:n,dimensionKeys:r}=gs();console.log(n,r);const o=t.useEditorStore(c=>{var h;return(h=c.card.queryConfig)==null?void 0:h.pivotColumns}),i=!!(o&&o.length>0),l=n.find(c=>c===s.label||c===s.name),u=l?n.indexOf(l):-1;return e.jsxs("div",{className:"space-y-3",children:[l&&e.jsx(bs,{idx:u,col:l,children:e.jsx(t.Editable,{enabled:!0,className:"w-[130px]",text:s.label||"",placeholder:"Enter label",onSave:c=>{a(s.id,{...s,label:c||s.name})},children:e.jsx(Ve,{className:"w-[130px]",children:s.label||s.name})})}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(t.Label,{children:"Pivot Header"}),e.jsx(t.Editable,{enabled:!0,text:s.aliasTemplate||"",placeholder:"{label} ({pivot})",onSave:c=>{a(s.id,{...s,aliasTemplate:c||""})},children:e.jsx(Ve,{className:"font-mono text-xs text-muted-foreground",children:s.aliasTemplate||"{label} ({pivot})"})})]})]})}function Wa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:l,updateMetricColumnOld:u,updatePivotByColumnOld:c}=t.useEditorActions(),{attributes:h,listeners:d,setNodeRef:x,transform:g,transition:p,isDragging:j}=t.useSortable({id:s.id,data:{type:a}}),m=g?{opacity:j?.5:void 0,transform:t.CSS.Translate.toString(g),transition:p}:void 0,v=t.isTextDataType(s.type);function f(C){const b=t.isNumberDataType(C.data_type),w=t.isTextDataType(C.data_type),I=t.isDateDataType(C.data_type),D=b?"number":w?"string":I?"date":"string";if(r===fe){if(w){const S={id:s.id,name:C.column_name,type:D,role:"groupby"};l(s.id,S)}if(I){const S={id:s.id,name:C.column_name,type:D,role:"groupby",label:Se(C.column_name,"month"),granularity:"month"};l(s.id,S)}}if(r===je){if(w){const S={id:s.id,name:C.column_name,type:D,role:"groupby"};c(s.id,S)}if(I){const S={id:s.id,name:C.column_name,type:D,label:Se(C.column_name,"month"),granularity:"month",role:"groupby"};c(s.id,S)}}if(r===ge){const S={id:s.id,name:C.column_name,type:D,role:"metric",label:Ee(C.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};u(s.id,S)}}function k(){if(r===ge)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(Qa,{column:s})})}function T(){const C=t.isDateDataType(s.type);if(r===ge)return e.jsx(Ja,{column:s});if((r===fe||r===je)&&C)return e.jsx(Ya,{column:s})}function E(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===fe||r===je)&&v}),children:e.jsx(Ka,{col:s,onChange:f,droppableId:r})})}function y(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(Mn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Yt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...d,...h,ref:x,style:m,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:[y(),T(),E()]}),o&&k()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function et({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var m,v;const{setNodeRef:l,isOver:u,over:c}=t.useDroppable({id:s}),h=t.useDndStore(f=>f.activeId),d=t.useEditorStore(f=>{var k;return(k=f.card)==null?void 0:k.type}),x=u||((v=(m=c==null?void 0:c.data)==null?void 0:m.current)==null?void 0:v.type)===o,g=h?r:n,p=o===ze?"Rows":o===Be?"Pivot Columns":"Columns";function j(){if(!g||g.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(t.SortableContext,{items:n==null?void 0:n.map(f=>f.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",x&&"border border-muted-foreground/20"),ref:l,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),d!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:p})]}),j(),e.jsx("div",{className:"space-y-2",children:g==null?void 0:g.map(f=>f.id===as.id?e.jsx(Xa,{},f.id):e.jsx(Wa,{droppableId:s,type:o,column:f,onRemoveColumn:i},f.id))})]})})}function Xa(){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 Ns({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:l,transition:u,isDragging:c}=t.useSortable({id:a,data:{type:n}}),h=l?{opacity:c?.5:void 0,transform:t.CSS.Translate.toString(l),transition:u}:void 0;return e.jsx("div",{...o,...r,ref:i,style:h,children:s})}function Za(){const s=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.orderBy})||[],a=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.groupByColumns})||[],n=t.useEditorStore(f=>{var k;return(k=f.card.queryConfig)==null?void 0:k.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),l=[...a,...n];if(l.length===0)return e.jsx(e.Fragment,{});const u=e.jsx(Js,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),c=e.jsx(qs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Hs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Vs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),x=l==null?void 0:l.filter(f=>!s.some(k=>k.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function g(f,k){const T=p(f);return T?T.role==="metric"?k==="asc"?h:d:k==="asc"?u:c:null}function p(f){return l.find(k=>k.id===f)}function j(f){const k=s.find(T=>T.columnId===f);if(k){const T={...k,direction:k.direction==="asc"?"desc":"asc"};i(T)}}const m=f=>{r({columnId:f.id,direction:"asc"})};function v(f){const k=s.find(T=>T.columnId===f);k&&o(k)}return e.jsx(t.SortableContext,{items:s.map(f=>ke(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),x.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:x,selectedOptions:[],onChange:f=>m(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(f=>{var k,T;return e.jsx(Ns,{id:ke(f.columnId),type:St,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(Yt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Ve,{className:"w-[175px] text-sm",children:((k=p(f.columnId))==null?void 0:k.label)||((T=p(f.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:g(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>v(f.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},ke(f.columnId))})]})})}function er(){const s=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),a=t.useEditorStore(v=>v.card.type),n=t.useDndStore(v=>v.previewGroupByColumns),r=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=t.useDndStore(v=>v.previewMetricColumns),i=t.useEditorStore(v=>{var f;return((f=v.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),l=t.useDndStore(v=>v.previewPivotColumns),{removeColumnFromGroupBy:u,removeColumnFromMetricColumns:c,removeColumnFromPivotBy:h}=t.useEditorActions();function d(v){u(v)}function x(v){c(v)}function g(v){h(v)}let p="Group By",j="Metrics",m="Stack By";return a==="table"&&(p="Rows",j="Metrics",m="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(xs,{iconClassName:"size-[19px]"}),e.jsxs(t.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(et,{onRemoveColumn:d,sortableType:ze,id:fe,label:p,columns:s,previewColumns:n}),e.jsx(et,{onRemoveColumn:g,sortableType:Be,id:je,label:m,columns:i,previewColumns:l}),e.jsx(et,{onRemoveColumn:x,sortableType:it,id:ge,label:j,columns:r,previewColumns:o}),e.jsx(Za,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Mt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,l]=L.useState(!1),{removeEditorFilter:u,clearEditorFilter:c}=t.useEditorActions(),h=t.useEditorStore(x=>{var g,p;return(p=(g=x.card.queryConfig)==null?void 0:g.filters)==null?void 0:p.some(j=>j.filterColumnName===a.name)});function d(x){u(x)}return e.jsx(Ns,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),h&&e.jsx("button",{onClick:()=>c(a),children:e.jsx(t.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:()=>d(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.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:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function tr({column:s,sortableType:a}){const n=t.useDashboardStore(T=>T.themeStyle),r=t.useEditorStore(T=>{var E,y;return(y=(E=T.card)==null?void 0:E.queryConfig)==null?void 0:y.filters}),o=t.useEditorStore(T=>{var E,y;return(y=(E=T.card.queryConfig)==null?void 0:E.filterColumns)==null?void 0:y.find(C=>C.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:l,selectedTableName:u}=t.useEditorAside(),c=L.useMemo(()=>{var T;return(T=r==null?void 0:r.find(E=>E.filterColumnName===s.name))==null?void 0:T.filterValue},[r,s.name]),h=L.useMemo(()=>Array.isArray(c)?c.map(T=>({id:T,value:T})):[],[c]),{updateEditorFilterValue:d}=t.useEditorActions(),x={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:g,isLoading:p,isFetching:j,isError:m}=t.useFilterQuery(x),v=L.useMemo(()=>{var E;return x.column?(E=g==null?void 0:g.records)==null?void 0:E.map(y=>{let C=x.column.split(".").slice(-1)[0].replace(/"/g,"");return y[C]===void 0&&(C=C.toLowerCase()),{id:y[C],value:y[C]}}):[]},[g,x.column]);function f(T){const E=T.map(y=>y.id);d(s.name,E)}function k(){return p||j?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):m?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(sr,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:v,onChange:f,selectedOptions:h,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Mt,{className:"w-60",id:s.id,sortableType:a,column:s,children:k()})}function sr({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,l;return(l=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:l.find(u=>u.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function nr({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:l}=t.useEditorAside(),u={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:c,isFetching:h,isError:d,data:x}=t.useFilterQuery(u),g=x==null?void 0:x.records,{dateRange:p,setDateRange:j,initialDateRange:m}=t.useDateRangeFromRecords(g),{updateEditorFilterValue:v}=t.useEditorActions();function f(E){var C,b;const y={gte:(C=E==null?void 0:E.from)==null?void 0:C.toISOString(),lte:(b=E==null?void 0:E.to)==null?void 0:b.toISOString()};v(s.name,y)}function k(){v(s.name,null,!0),j(m)}function T(){return c||h?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):d?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):g?e.jsx(t.DateRangePopover,{title:u.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:p,setDateRange:j,onApply:f,onClear:k}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Mt,{className:"w-72",id:s.id,sortableType:a,column:s,children:T()})}function ar({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var j,m;const{setNodeRef:i,isOver:l,over:u}=t.useDroppable({id:s}),c=t.useDndStore(v=>v.activeId),h={},d=l||((m=(j=u==null?void 0:u.data)==null?void 0:j.current)==null?void 0:m.type)===o;function x(){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 g(v){const f=t.isDateDataType(v.type);return v.id===as.id?e.jsx(Mt,{id:v.id,sortableType:o,column:v,children:e.jsx(rr,{})},v.id):f?e.jsx(nr,{droppableId:s,sortableType:o,column:v},v.id):e.jsx(tr,{droppableId:s,sortableType:o,column:v},v.id)}const p=c?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(v=>v.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",d&&"border border-muted-foreground/20"),ref:i,style:h,children:[e.jsx(t.Label,{className:"text-sm",children:a}),x(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:p==null?void 0:p.map(v=>g(v))})]})})}function rr(){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 or(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ar,{onRemoveColumn:r,sortableType:ct,id:lt,label:"Filters",columns:s,previewColumns:a})})}function ir(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);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(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(wn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(is,{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(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function lr(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(u=>u.isShowingVisual),r=t.useEditorStore(u=>u.showAIDialog),o=t.useEditorStore(u=>u.isDevMode);L.useEffect(()=>{var u,c,h,d;r?((u=s.current)==null||u.resize(0),(c=a.current)==null||c.resize(0)):((h=s.current)==null||h.resize(25),(d=a.current)==null||d.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ra,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx($a,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Le,{})})]}):e.jsx(Le,{})})]})}function l(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(er,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(ir,{}),e.jsx(or,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Le,{})})]})})]}):e.jsx(Le,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():l()})}function cr(s,a){const[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:l}=t.useSemaphorContext(),u=t.useEditorStore(G=>{var Q;return(Q=G==null?void 0:G.card)==null?void 0:Q.sql}),c=t.useEditorStore(G=>G.isDevMode),h=t.useEditorStore(G=>{var Q;return(Q=G==null?void 0:G.card)==null?void 0:Q.python}),{setCardPython:d,setCardSql:x,setRunSql:g,switchCardType:p,setQueryConfig:j}=t.useEditorActions(),m=t.useEditorStore(G=>G.currentAssitantScope)||[],v=t.useEditorStore(G=>G.userInputForAI),f=t.useEditorStore(G=>G.triggerAIRun),k=t.useEditorStore(G=>G.selectedDatabaseName),T=t.useEditorStore(G=>G.selectedTableName),E=t.useEditorStore(G=>G.selectedConnectionId),y=t.useEditorStore(G=>G.selectedSchemaName),C=t.useDashboardStore(G=>G.dashboard.aiScopeTables),{setTriggerAIRun:b,setCurrentAssitantScope:w,setCardConfig:I}=t.useEditorActions(),{selectedDatamodelName:D,connectionType:S,selectedDatamodelId:F}=t.useEditorAside(),{messages:O,setMessages:A,reload:N,error:M,append:z,input:R,setInput:q,status:B,handleInputChange:K,handleSubmit:J,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${l==null?void 0:l.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:c,aiContext:s},maxSteps:10,onError:G=>{console.log("on error",G)},onToolCall:Y,onFinish(G,Q){_(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{f&&v&&(K({target:{value:v}}),setTimeout(()=>{J(),b(!1)},100))},[f,J,v,b,K]);async function Y({toolCall:G}){if(["createChartFromSql","createForecast"].includes(G.toolName)){const Q=G.args.sql,se=G.args.python,me=G.args.chartType;return p(me),x(Q),d(se),g(!0),{status:"success",message:"Let the user know that chart is created"}}else if(G.toolName==="getTableColumns")r("Getting table columns...");else{if(G.toolName==="getUserSql")return u?{status:"success",sql:u,python:h||""}:{status:"error",message:"No SQL found"};if(G.toolName==="getCurrentTableScope")return r("Getting table scope..."),U(),{status:"success",tables:m};if(G.toolName==="generateQueryConfig"){r("Generating query config...");const Q=G.args.chartType,se=G.args.queryConfig;return G.args.cardConfig,p(Q),I(se),x(void 0),d(void 0),g(!0),{status:"success",queryConfig:se}}else r("Analyzing...")}}function _(G){i(Q=>Q?{promptTokens:Q.promptTokens+G.promptTokens,completionTokens:Q.completionTokens+G.completionTokens,totalTokens:Q.totalTokens+G.totalTokens}:G)}function V(G){const Q=t.removeFromScopeArray(m,G);P(Q)}function P(G){const Q=t.sanitizeAIScope(G);w(Q),A(se=>[...se,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function H(){const G={databaseName:k||"",schemaName:y||"",tableName:T||"",datamodelId:F||"",datamodelName:t.resolveDatamodelName(D),connectionId:E||"",connectionType:S||""},Q=t.dedup([...m,G]);P(Q)}function U(){const G={databaseName:k||"",schemaName:y||"",tableName:T||"",datamodelName:t.resolveDatamodelName(D),connectionId:E||"",connectionType:S||"",datamodelId:F||""};if(!t.isInAiScopeArray([...C||[],...m],G)||m.length===0){const se=t.dedup([...C||[],...m,G]).filter(me=>me.connectionId===G.connectionId);P(se)}}const Z=!["ready","error"].includes(B),de=t.getErrorMessage(M);return{messages:O,setMessages:A,reload:N,append:z,input:R,setInput:q,isLoading:Z,handleSetAIScope:U,handleAddCurrentTableToScope:H,removeFromCurrentSelections:V,currentAssitantScope:m,setCurrentAssitantScope:w,handleInputChange:K,handleSubmit:J,stop:$,chatStatus:B,toolStatus:n,llmUsage:o,onFinish:a,errorMessage:de}}const dr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Gt(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[l,u]=L.useState(!1),[c,h]=L.useState(!1),[d,x]=L.useState({selectedEntities:[]}),g=t.useDashboardStore(P=>P.dashboard.aiContext),p=t.useEditorStore(P=>P.card.dataSource),j=t.useEditorStore(P=>P.actions.setCardSql),m=t.useEditorStore(P=>P.actions.setRunSql),v=t.useEditorStore(P=>P.showAIDialog),f=t.useDashboardStore(P=>P.handleOpenAssistantProfile),{setShowAIDialog:k,setCardPython:T}=t.useEditorActions(),{setDataSource:E}=t.useEditorActions(),{assistantProfile:y}=t.useAssistantProfile(),{messages:C,setMessages:b,reload:w,append:I,input:D,setInput:S,isLoading:F,handleInputChange:O,handleSubmit:A,stop:N,chatStatus:M,llmUsage:z,errorMessage:R}=cr(d);t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:C}),L.useEffect(()=>{var P;v&&((P=a.current)==null||P.focus())},[v]);function q(P,H){H==="sql"?(j(P),m(!0)):H==="python"&&(T(P),m(!0))}function B(){var U;const P=(U=g==null?void 0:g.selectedEntities)==null?void 0:U[0],H={connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"",mode:(P==null?void 0:P.type)==="dataset"?"semanticModel":"database",dbSelection:{database:(P==null?void 0:P.database)||"",schema:(P==null?void 0:P.schema)||"",entityType:(P==null?void 0:P.type)||"table"},selectedEntities:(g==null?void 0:g.selectedEntities)||[]};E(H),h(!0)}function K(){d.selectedEntities.length===0&&x({selectedEntities:(g==null?void 0:g.selectedEntities)||[]})}function J(P){K();const H={role:"user",content:P.title+" "+P.subtitle};I(H)}function $(P){K(),I({role:"user",content:P})}function Y(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function _(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const V=(D==null?void 0:D.length)===0&&(C==null?void 0:C.filter(P=>P.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:[_(),f&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(y==null?void 0:y.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",onClick:B,children:e.jsx(t.Settings,{className:"size-4"})}),Y(),e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",onClick:()=>{b([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{k(!1)},children:e.jsx(En,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,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(t.PrintMessages,{messages:C,showTools:o,handleRun:q,showSystemMessage:l}),e.jsx(t.ChatStatus,{messages:C,chatStatus:M,errorMessage:R})]})}),e.jsxs("div",{className:"mb-3",children:[V&&!y&&e.jsx(t.Placeholders,{onClick:J,placeholders:dr}),e.jsx("div",{children:V&&y&&e.jsx(t.SeedQuestions,{seedQuestions:y.seedQuestions||[],handleSeedQuestionClick:$})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:S,stop:N,input:D,localAiContext:d,setLocalAiContext:x,handleInputChange:O,handleSubmit:P=>{K(),A(P)},isLoading:F,onFocus:()=>{}}),z&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",z.promptTokens," prompt tokens,"," ",z.completionTokens," completion tokens,"," ",z.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{open:c,onOpenChange:h,dataSource:p||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function ur(s){return s.flatMap(a=>a.columns.map(n=>({id:`${a.entityId}-${n.name}`,name:n.name,dataType:n.dataType,qualifiedEntityName:a.qualifiedEntityName,label:n.label||t.toTitleCase(n.name),description:n.description,entityId:a.entityId,entityName:a.entityName,entityType:a.entityType})))}function mr(s){if(s.type==="table"||s.type==="view"){if(s.database&&s.schema)return`${s.database}.${s.schema}.${s.name}`;if(s.database)return`${s.database}.${s.name}`}return s.name}function Me(s){var j;const a=t.useDashboardStore(m=>m.authToken)||s,{hasSchemaSupport:n}=t.useSelectedConnection(s),r=t.useEditorStore(m=>{var v;return(v=m.card.dataSource)==null?void 0:v.connectionId}),o=t.useEditorStore(m=>{var v,f;return(f=(v=m.card.dataSource)==null?void 0:v.selectedEntities)==null?void 0:f.filter(k=>k.type==="model")})||[],i=t.useEditorStore(m=>{var v,f;return(f=(v=m.card.dataSource)==null?void 0:v.selectedEntities)==null?void 0:f.filter(k=>k.type==="table"||k.type==="view")})||[];function l(m){return m.type==="model"?!!r&&!!m.id:m.type==="table"||m.type==="view"?n?!!r&&!!m.name&&!!m.database&&!!m.schema:!!r&&!!m.name&&!!m.database:!1}const u=[...o,...i],c=zs({queries:u.map(m=>({queryKey:["columns",r,m],queryFn:()=>t.getRequest("https://semaphor.cloud/api/v1/columns",(a==null?void 0:a.accessToken)||"",m.type==="model"?{connection_id:r,datamodel_id:m.id,database_name:"",schema_name:"",table_name:""}:{connection_id:r,datamodel_id:"",database_name:m.database,schema_name:m.schema,table_name:m.name}),enabled:!!r&&l(m)}))}),h=c.some(m=>m.isPending),d=c.some(m=>m.isError),x=(j=c.find(m=>m.isError))==null?void 0:j.error,g=c.map((m,v)=>{var T;const f=u[v],k=mr(f);return{entityId:f.id||f.name,entityType:f.type,entityName:f.name,label:f.label,description:f.description,qualifiedEntityName:k,columns:(T=m.data)==null?void 0:T.columns.map(E=>({id:`${f.name}-${E.column_name}`,name:E.column_name,dataType:E.data_type,label:E.label||t.toLabel(E.column_name),description:E.description||"",qualifiedEntityName:k,entityId:f.id||f.name,entityName:f.name,entityType:f.type}))}}).filter(m=>{var v;return((v=m==null?void 0:m.columns)==null?void 0:v.length)>0})||[],p=ur(g);return{columnGroups:g,columns:p,isLoading:h,hasError:d,error:x,refetch:()=>{c.forEach(m=>m.refetch())}}}function hr({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:l}=t.useSortable({id:s.id}),[u,c]=L.useState(!1),h={transform:t.CSS.Transform.toString(o),transition:i},d=t.getDataType(s.dataType),g=(p=>{const j=(p||"").toLowerCase();switch(t.getDataType(j)){case"number":return gt;case"date":return t.Calendar;case"boolean":return Xt;case"json":return sn;case"geo":return Nn;default:return Zt}})(s.dataType);return e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${l?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>c(!u),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(g,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",d==="string"?"text-blue-500":"",d==="number"?"text-green-500":"",d==="date"?"text-purple-500":"",d==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm dark:text-muted-foreground ${u?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:s.label||s.name}),s.label&&s.label!==s.name&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Name: ",s.name]}),e.jsx("p",{className:"text-xs text-gray-500",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type: ",s.dataType]})]})})]})}),e.jsx("button",{onClick:p=>{p.stopPropagation(),c(!u)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:u?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),u&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function xr({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(hr,{field:o},o.id))})})]})}function pr(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),l=t.useEditorStore(E=>E.card.dataSource),{columns:u=[],columnGroups:c=[],isLoading:h,error:d}=Me(),x=u.filter(E=>E.name.toLowerCase().includes(s.toLowerCase())||E.dataType.toLowerCase().includes(s.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),g=E=>E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency"?"metrics":"dimensions",j=(o==="all"?x:x.filter(E=>g(E)===o)).reduce((E,y)=>{const C=y.qualifiedEntityName||"Other Fields";return E[C]||(E[C]={label:t.toLabel(y.entityName),fields:[]}),E[C].fields.push(y),E},{});L.useEffect(()=>{const E=Object.keys(j);r(new Set(E))},[Object.keys(j).join(",")]);const m=E=>{const y=new Set(n);y.has(E)?y.delete(E):y.add(E),r(y)},v=x.filter(E=>g(E)==="dimensions").length,f=x.filter(E=>g(E)==="metrics").length,k=x.filter(E=>g(E)==="calculated").length,T=x.length>0;return h?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(ce,{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(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(t.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(t.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-[290px] grow flex-col gap-2 pb-6",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-2 p-1 pb-0",children:[u.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:E=>a(E.target.value)})}),T&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:E=>i(E),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(ut,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Ws,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),e.jsxs(t.ScrollArea,{className:"flex-1",children:[e.jsxs("div",{className:"space-y-2 p-1 pt-0",children:[Object.entries(j).map(([E,y])=>{const C=c.find(b=>b.entityName===E)||{entityName:E,label:y.label};return e.jsx(xr,{entityGroup:C,fields:y.fields,isOpen:n.has(E),onToggle:()=>m(E)},E)}),Object.keys(j).length===0&&u.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(j).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function fr(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(pr,{})," "]})}function gr({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),l=()=>{const C=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),i(new Set([...o,b.id]))},u=C=>{r({...n,joins:n.joins.filter(b=>b.id!==C)}),i(new Set([...o].filter(b=>b!==C)))},c=(C,b)=>{var S,F;const w=n.joins.find(O=>O.id===C);if(!w)return;const I={...w,...b},D=n.joins.map(O=>O.id===C?I:O);if((S=I.source)!=null&&S.name&&((F=I.target)!=null&&F.name)&&I.joinKeyGroups[0].keys.length===0){const O=a.find(z=>{var R;return z.name===((R=I.source)==null?void 0:R.name)}),A=a.find(z=>{var R;return z.name===((R=I.target)==null?void 0:R.name)}),N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="},M=[...I.joinKeyGroups];M[0]={...M[0],keys:[N]},I.joinKeyGroups=M,D[D.findIndex(z=>z.id===C)]=I}r({...n,joins:D})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:l,removeJoin:u,updateJoin:c,moveJoinUp:C=>{const b=n.joins.findIndex(w=>w.id===C);if(b>0){const w=[...n.joins],I={...w[b]},D={...w[b-1]};w[b]=D,w[b-1]=I,w.forEach((F,O)=>{F.sequence=O+1});const S={...n,joins:w};r(S)}},moveJoinDown:C=>{const b=n.joins.findIndex(w=>w.id===C);if(b<n.joins.length-1){const w=[...n.joins],I={...w[b]},D={...w[b+1]};w[b]=D,w[b+1]=I,w.forEach((F,O)=>{F.sequence=O+1});const S={...n,joins:w};r(S)}},toggleJoinExpansion:C=>{const b=new Set(o);b.has(C)?b.delete(C):b.add(C),i(b)},getAvailableSourceEntities:C=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(I=>I.id===C);if(b===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,b).forEach(I=>{w.add(I.source.name),w.add(I.target.name)}),a.filter(I=>w.has(I.name))},getAvailableTargetEntities:C=>a.filter(b=>b.name!==C),addJoinKeyGroup:C=>{const b=n.joins.find(I=>I.id===C);if(!b)return;const w=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];c(C,{joinKeyGroups:w})},updateGroupOperator:(C,b,w)=>{const I=n.joins.find(S=>S.id===C);if(!I)return;const D=[...I.joinKeyGroups];D[b]={...D[b],operator:w},c(C,{joinKeyGroups:D})},removeJoinKeyGroup:(C,b)=>{const w=n.joins.find(D=>D.id===C);if(!w)return;const I=[...w.joinKeyGroups];I.splice(b,1),c(C,{joinKeyGroups:I})},addJoinKey:(C,b)=>{const w=n.joins.find(O=>O.id===C);if(!w)return;const I=a.find(O=>O.name===w.source.name),D=a.find(O=>O.name===w.target.name),S=[...w.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${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"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="};S[b]={...S[b],keys:[...S[b].keys,F]},c(C,{joinKeyGroups:S})},updateJoinKey:(C,b,w,I,D)=>{const S=n.joins.find(M=>M.id===C);if(!S)return;const F=a.find(M=>M.name===S.source.name),O=a.find(M=>M.name===S.target.name),A=[...S.joinKeyGroups],N=A[b].keys[w];I==="sourceColumnName"&&F?A[b].keys[w]={...N,source:{...N.source,name:D}}:I==="targetColumnName"&&O?A[b].keys[w]={...N,target:{...N.target,name:D}}:I==="operator"&&(A[b].keys[w]={...N,operator:D}),c(C,{joinKeyGroups:A})},removeJoinKey:(C,b,w)=>{const I=n.joins.find(S=>S.id===C);if(!I)return;const D=[...I.joinKeyGroups];D[b].keys.splice(w,1),c(C,{joinKeyGroups:D})},generateSQLPreview:()=>{const C=[...n.joins].sort((I,D)=>I.sequence-D.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
405
405
  FROM ${b.name}`;return C.forEach(I=>{const D=a.find(O=>O.name===I.target.name);if(!D)return;const S=I.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const A=O.keys.filter(N=>{var M,z,R,q;return((M=N.source)==null?void 0:M.name)&&((z=N.target)==null?void 0:z.name)&&((R=N.source)==null?void 0:R.entityName)&&((q=N.target)==null?void 0:q.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return A.length>1?`(${A.join(` ${O.operator} `)})`:A[0]}).filter(Boolean),F=S.length>1?S.join(" OR "):S[0]||"condition_here";w+=`
406
406
  ${I.joinType} JOIN ${D.name}
407
- ON ${F}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(I=>!I.source.name||!I.target.name)||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.length===0))||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function jr({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(S=>S.card.config);const{columnGroups:l}=Te(),{joinPlan:u,expandedJoins:c,setJoinPlan:h,addJoin:d,removeJoin:x,updateJoin:j,moveJoinUp:p,moveJoinDown:g,toggleJoinExpansion:m,getAvailableSourceEntities:v,getAvailableTargetEntities:f,addJoinKeyGroup:k,updateGroupOperator:T,removeJoinKeyGroup:E,addJoinKey:y,updateJoinKey:C,removeJoinKey:b,generateSQLPreview:w,isValidConfiguration:I}=gr({initialJoinPlan:s,availableDataSources:a}),D=S=>{const F=l.find(O=>O.entityName===S);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:u.baseEntity.name,onValueChange:S=>{const F=a.find(O=>O.name===S);h({...u,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:S,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(S=>e.jsx(t.SelectItem,{value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-gray-500",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 bg-gray-100 p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-gray-600",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",u.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),u.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-gray-500",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:u.joins.map(S=>{const F=a.find(N=>N.name===S.source.name),O=a.find(N=>N.name===S.target.name),A=c.has(S.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.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(t.Badge,{children:S.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",S.sequence,F&&O&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",O.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),disabled:S.sequence===1,children:e.jsx(_e,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(S.id),disabled:S.sequence===u.joins.length,children:e.jsx(qe,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>m(S.id),children:A?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),A&&e.jsxs(t.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(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:S.source.name,onValueChange:N=>{const M=a.find(z=>z.name===N);j(S.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:v(S.id).map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name]})},N.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:S.joinType,onValueChange:N=>j(S.id,{joinType:N}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:S.target.name,onValueChange:N=>{const M=a.find(z=>z.name===N);j(S.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!S.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:S.source.name?f(S.source.name).map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,N.name===S.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},N.name)):[]})]})]})]}),S.source.name&&S.target.name&&F&&O&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>k(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((N,M)=>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(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.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(t.Select,{value:N.operator,onValueChange:z=>T(S.id,M,z),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(S.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[N.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:N.keys.map((z,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:N.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:z.source.name,onValueChange:q=>C(S.id,M,R,"sourceColumnName",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:D(S.source.name).map(q=>e.jsx(t.SelectItem,{value:q.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:q.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:q.dataType})]})},q.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:z.operator,onValueChange:q=>C(S.id,M,R,"operator",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"=",children:"="}),e.jsx(t.SelectItem,{value:"<",children:"<"}),e.jsx(t.SelectItem,{value:">",children:">"}),e.jsx(t.SelectItem,{value:"<=",children:"<="}),e.jsx(t.SelectItem,{value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:z.target.name,onValueChange:q=>C(S.id,M,R,"targetColumnName",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:D(S.target.name).map(q=>e.jsx(t.SelectItem,{value:q.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:q.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:q.dataType})]})},q.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(S.id,M,R),children:e.jsx(t.X,{className:"size-3.5"})})]},z.id||R))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>y(S.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},N.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(u),disabled:!I(),children:"Save"})]})]})}function $t({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:l,onCancel:u}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsx(t.DialogContent,{className:"max-w-4xl",children:e.jsx(jr,{joinPlan:r,availableDataSources:o,onSave:l,onCancel:u,onRemove:i})}),s]})}function yr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.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=[...s].sort((l,u)=>l.sequence-u.sequence),i=n.find(l=>l.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(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(l=>{const u=n.find(c=>c.name===l.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(t.Badge,{variant:"outline",className:"text-xs",children:l.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(t.Badge,{variant:"secondary",className:"text-xs",children:u==null?void 0:u.type}),e.jsx("span",{className:"text-xs font-medium",children:u==null?void 0:u.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const l=n.find(c=>c.name===o.source.name),u=n.find(c=>c.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(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[l==null?void 0:l.name," → ",u==null?void 0:u.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((c,h)=>c+h.keys.length,0)," ","condition",o.joinKeyGroups.reduce((c,h)=>c+h.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 br(){var x,j;Te(),t.useEditorStore(p=>p.card.dataSource);const s=t.useEditorStore(p=>p.frame),a=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>p.actions.updateCardConfig),r=((x=a==null?void 0:a.config)==null?void 0:x.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[o,i]=L.useState(!1),l=((j=a==null?void 0:a.dataSource)==null?void 0:j.selectedEntities)||[],u=p=>{s.activeCardId&&(n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:p}),i(!1))},c=()=>{n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:void 0})},h=()=>{i(!1)},d=()=>{const p=[...r.joins].sort((v,f)=>v.sequence-f.sequence),g=r.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let m=`SELECT *
408
- FROM ${g.name}`;return p.forEach(v=>{const f=l.find(E=>E.name===v.target.name);if(!f)return;const k=v.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const y=E.keys.filter(C=>{var b,w,I,D;return((b=C.source)==null?void 0:b.name)&&((w=C.target)==null?void 0:w.name)&&((I=C.source)==null?void 0:I.entityName)&&((D=C.target)==null?void 0:D.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return y.length>1?`(${y.join(` ${E.operator} `)})`:y[0]}).filter(Boolean),T=k.length>1?k.join(" OR "):k[0]||"condition_here";m+=`
407
+ ON ${F}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(I=>!I.source.name||!I.target.name)||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.length===0))||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function jr({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(S=>S.card.config);const{columnGroups:l}=Me(),{joinPlan:u,expandedJoins:c,setJoinPlan:h,addJoin:d,removeJoin:x,updateJoin:g,moveJoinUp:p,moveJoinDown:j,toggleJoinExpansion:m,getAvailableSourceEntities:v,getAvailableTargetEntities:f,addJoinKeyGroup:k,updateGroupOperator:T,removeJoinKeyGroup:E,addJoinKey:y,updateJoinKey:C,removeJoinKey:b,generateSQLPreview:w,isValidConfiguration:I}=gr({initialJoinPlan:s,availableDataSources:a}),D=S=>{const F=l.find(O=>O.entityName===S);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:u.baseEntity.name,onValueChange:S=>{const F=a.find(O=>O.name===S);h({...u,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:S,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(S=>e.jsx(t.SelectItem,{value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-gray-500",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 bg-gray-100 p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-gray-600",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",u.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),u.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-gray-500",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:u.joins.map(S=>{const F=a.find(N=>N.name===S.source.name),O=a.find(N=>N.name===S.target.name),A=c.has(S.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.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(t.Badge,{children:S.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",S.sequence,F&&O&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",O.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),disabled:S.sequence===1,children:e.jsx(_e,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>j(S.id),disabled:S.sequence===u.joins.length,children:e.jsx(qe,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>m(S.id),children:A?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),A&&e.jsxs(t.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(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:S.source.name,onValueChange:N=>{const M=a.find(z=>z.name===N);g(S.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:v(S.id).map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name]})},N.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:S.joinType,onValueChange:N=>g(S.id,{joinType:N}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:S.target.name,onValueChange:N=>{const M=a.find(z=>z.name===N);g(S.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!S.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:S.source.name?f(S.source.name).map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,N.name===S.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},N.name)):[]})]})]})]}),S.source.name&&S.target.name&&F&&O&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>k(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((N,M)=>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(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.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(t.Select,{value:N.operator,onValueChange:z=>T(S.id,M,z),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(S.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[N.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:N.keys.map((z,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:N.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:z.source.name,onValueChange:q=>C(S.id,M,R,"sourceColumnName",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:D(S.source.name).map(q=>e.jsx(t.SelectItem,{value:q.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:q.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:q.dataType})]})},q.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:z.operator,onValueChange:q=>C(S.id,M,R,"operator",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"=",children:"="}),e.jsx(t.SelectItem,{value:"<",children:"<"}),e.jsx(t.SelectItem,{value:">",children:">"}),e.jsx(t.SelectItem,{value:"<=",children:"<="}),e.jsx(t.SelectItem,{value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:z.target.name,onValueChange:q=>C(S.id,M,R,"targetColumnName",q),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:D(S.target.name).map(q=>e.jsx(t.SelectItem,{value:q.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:q.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:q.dataType})]})},q.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(S.id,M,R),children:e.jsx(t.X,{className:"size-3.5"})})]},z.id||R))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>y(S.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},N.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(u),disabled:!I(),children:"Save"})]})]})}function $t({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:l,onCancel:u}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsx(t.DialogContent,{className:"max-w-4xl",children:e.jsx(jr,{joinPlan:r,availableDataSources:o,onSave:l,onCancel:u,onRemove:i})}),s]})}function yr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.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=[...s].sort((l,u)=>l.sequence-u.sequence),i=n.find(l=>l.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(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(l=>{const u=n.find(c=>c.name===l.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(t.Badge,{variant:"outline",className:"text-xs",children:l.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(t.Badge,{variant:"secondary",className:"text-xs",children:u==null?void 0:u.type}),e.jsx("span",{className:"text-xs font-medium",children:u==null?void 0:u.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const l=n.find(c=>c.name===o.source.name),u=n.find(c=>c.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(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[l==null?void 0:l.name," → ",u==null?void 0:u.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((c,h)=>c+h.keys.length,0)," ","condition",o.joinKeyGroups.reduce((c,h)=>c+h.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 br(){var x,g;Me(),t.useEditorStore(p=>p.card.dataSource);const s=t.useEditorStore(p=>p.frame),a=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>p.actions.updateCardConfig),r=((x=a==null?void 0:a.config)==null?void 0:x.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[o,i]=L.useState(!1),l=((g=a==null?void 0:a.dataSource)==null?void 0:g.selectedEntities)||[],u=p=>{s.activeCardId&&(n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:p}),i(!1))},c=()=>{n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:void 0})},h=()=>{i(!1)},d=()=>{const p=[...r.joins].sort((v,f)=>v.sequence-f.sequence),j=r.baseEntity;if(!j.name)return"SELECT * FROM table -- Please select a base entity";let m=`SELECT *
408
+ FROM ${j.name}`;return p.forEach(v=>{const f=l.find(E=>E.name===v.target.name);if(!f)return;const k=v.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const y=E.keys.filter(C=>{var b,w,I,D;return((b=C.source)==null?void 0:b.name)&&((w=C.target)==null?void 0:w.name)&&((I=C.source)==null?void 0:I.entityName)&&((D=C.target)==null?void 0:D.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return y.length>1?`(${y.join(` ${E.operator} `)})`:y[0]}).filter(Boolean),T=k.length>1?k.join(" OR "):k[0]||"condition_here";m+=`
409
409
  ${v.joinType} JOIN ${f.name}
410
- ON ${T}`}),m};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:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>i(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(yr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx($t,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx($t,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsxs(t.Button,{onClick:()=>i(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function vr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(d=>d.card.dataSource),{updateDataSource:i}=t.useEditorActions(),[l,u]=L.useState([]),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return L.useEffect(()=>{s&&u((o==null?void 0:o.selectedEntities)||[])},[s,o==null?void 0:o.selectedEntities]),e.jsxs("div",{className:"flex w-80 flex-col border-r bg-background",children:[e.jsxs("div",{className:"",children:[e.jsx("div",{className:t.cn("p-4",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4 text-gray-500"}):e.jsx(t.ChevronRight,{className:"h-4 w-4 text-gray-500"}),e.jsx(t.Database,{className:"h-5 w-5 text-cyan-600"}),e.jsx("h2",{className:"font-semibold text-gray-900",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-8",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-4 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((d,x)=>e.jsxs(t.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:[d.name,e.jsx("button",{onClick:j=>{j.stopPropagation();const p=h.selectedEntities.filter(g=>!(g.name===d.name&&g.type===d.type));u(p),i({...c,...o,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 text-red-500"})})]},`${d.type}-${d.name}-${x}`)),h.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})]}),e.jsx(br,{})]})]}),e.jsx(fr,{}),e.jsx(t.DataSourceDialog,{dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:h,fallbackDataSource:c})]})}const Cr=[{id:"table",icon:He,label:"Table"},{id:"bar",icon:Ge,label:"Bar Chart"},{id:"line",icon:$e,label:"Line Chart"},{id:"stackedBar",icon:dt,label:"Stacked Bar Chart"},{id:"stackedLine",icon:It,label:"Stacked Line Chart"},{id:"scatter",icon:xt,label:"Scatter Chart"},{id:"bubble",icon:kt,label:"Bubble Chart"},{id:"pie",icon:ht,label:"Pie Chart"},{id:"doughnut",icon:pt,label:"Doughnut Chart"},{id:"funnel",icon:Et,label:"Funnel Chart"},{id:"radar",icon:yt,label:"Radar Chart"},{id:"polarArea",icon:wt,label:"Polar Area Chart"},{id:"tornado",icon:vt,label:"Tornado Chart"},{id:"range",icon:mt,label:"Range Chart"},{id:"kpi",icon:Dt,label:"KPI"},{id:"text",icon:Jt,label:"Text"},{id:"map",icon:jt,label:"Map"},{id:"custom",icon:bt,label:"Custom"}];function Nr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(h){i(null),r({}),n(h),["kpi","custom","text","map"].includes(h)&&(o(!0),u(void 0)),a(h)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:Cr.map(h=>{const d=h.icon;return e.jsx(t.SelectItem,{value:h.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{children:h.label})]})},h.id)})})]})})}const Ss=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function Sr({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:l=>{r(l.target.value),i(!0)},onFocus:()=>i(!0),onClick:l=>l.stopPropagation(),className:"h-8 text-xs",onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):l.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function wr({aliasTemplate:s,onAliasTemplateChange:a}){var c;const[n,r]=L.useState(s),[o,i]=L.useState(!1),l=(c=t.useEditorStore(h=>{var d;return(d=h.card.config)==null?void 0:d.pivotByColumns}))==null?void 0:c[0],u=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.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(t.Input$1,{placeholder:u,value:o?n:s,onChange:h=>{r(h.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&o&&n!==s?(a(n),i(!1)):h.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function kr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},h=x=>{const j={...s};delete j[x],a(j)},d=x=>{const j={...s};delete j[x],j[o]=l,a(j),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,j],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?d(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:l,onChange:g=>u(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?d(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>d(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),u(j)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:j,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),u(j)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:c,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Er({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,hasPivotColumns:x=!1}){const{attributes:j,listeners:p,setNodeRef:g,transform:m,transition:v,isDragging:f}=t.useSortable({id:s.id}),[k,T]=L.useState(!1),[E,y]=L.useState(s.dateFormat||"YYYY-MM-DD"),[C,b]=L.useState(s.customFormat||""),[w,I]=L.useState(!!s.customFormat),[D,S]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,N]=L.useState(s.valueAliases||{}),M=G=>{G==="custom"?I(!0):(I(!1),y(G),a==="groupBy"&&h&&h(G,""))},z=G=>{b(G),a==="groupBy"&&h&&h("custom",G)},R=G=>{S(G),a==="groupBy"&&d&&d(G)},q=G=>{O(G),l&&l(G)},B=G=>{N(G),u&&u(G)},K={transform:t.CSS.Transform.toString(m),transition:v},J=t.getDataType(s.dataType),$=J==="date",U=[{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..."}];return e.jsxs("div",{ref:g,style:K,...j,...p,className:`group flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(Ss,{dataType:J}),e.jsx("span",{className:"max-w-[180px] flex-1 overflow-hidden truncate text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),T(!k)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${k?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",o);const V=o==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",V),i(V)},children:o==="asc"?e.jsx(_e,{className:"h-3 w-3"}):e.jsx(qe,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),n()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),k&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("span",{className:"flex-1 overflow-hidden truncate px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),a!=="pivotBy"&&e.jsx(Sr,{label:s.label??"",onLabelChange:r}),$&&a!=="groupBy"&&e.jsx("div",{className:"space-y-1",children:e.jsxs(t.Select,{defaultValue:"day",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})}),$&&a==="groupBy"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Granularity"}),e.jsxs(t.Select,{value:D,onValueChange:R,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Date Format"}),e.jsxs(t.Select,{value:w?"custom":E,onValueChange:M,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:U.map(G=>e.jsx(t.SelectItem,{value:G.value,children:G.label},G.value))})]}),w&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:C,onChange:G=>{G.stopPropagation(),z(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),a==="metrics"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:G=>{c&&c(G)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),x&&e.jsxs(e.Fragment,{children:[e.jsx(wr,{aliasTemplate:F,onAliasTemplateChange:q}),e.jsx(kr,{valueAliases:A,onValueAliasesChange:B})]})]})]})]})}function Fe({zone:s,fields:a,label:n,placeholder:r,onRemove:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:h,onValueAliasesChange:d,shouldShow:x,hasPivotColumns:j=!1}){const{isOver:p,setNodeRef:g}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),v=t.useEditorStore(T=>T.card),f=a.length>0,k=(T,E)=>{var C;!((C=v.config)!=null&&C.sortByColumns)||v.config.sortByColumns.findIndex(b=>b.id===T)===-1||m(v.id,T,{direction:E})};return s==="sortBy"&&x===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsx(t.Label,{className:"mb-2 block text-sm font-medium",children:n}),e.jsx("div",{ref:g,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${p?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((T,E)=>{const C=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Er,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:b=>i(E,b),sortDirection:C,onSortDirectionChange:b=>k(T.id,b),onAggregationChange:l?b=>l(E,b):void 0,onAliasTemplateChange:h?b=>h(E,b):void 0,onValueAliasesChange:d?b=>d(E,b):void 0,onDateFormatChange:u?(b,w)=>u(E,b,w):void 0,onGranularityChange:c?b=>c(E,b):void 0,hasPivotColumns:j})})},T.id)})})})})]})}function Ir({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,onRemoveField:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:h,onValueAliasesChange:d}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:s,label:"Group By",placeholder:"Drop fields to group data",onRemove:x=>o("groupBy",x),onLabelChange:(x,j)=>i("groupBy",x,j),onDateFormatChange:(x,j,p)=>u&&u(x,j,p),onGranularityChange:(x,j)=>c&&c(x,j)}),e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Pivot By",placeholder:"Drop fields to pivot data",onRemove:x=>o("pivotBy",x),onLabelChange:(x,j)=>i("pivotBy",x,j)}),e.jsx(Fe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:x=>o("metrics",x),onLabelChange:(x,j)=>i("metrics",x,j),onAggregationChange:l,onAliasTemplateChange:h,onValueAliasesChange:d,hasPivotColumns:a.length>0}),r&&r.length>0&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields to sort data",onRemove:x=>o("sortBy",x),onLabelChange:(x,j)=>i("sortBy",x,j),shouldShow:s.length>0||a.length>0||n.length>0})]})}function Dr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,onAliasTemplateChange:x,onValueAliasesChange:j}){t.useEditorStore(g=>g.showAIDialog);const{setShowAIDialog:p}=t.useEditorActions();return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-5 w-5 text-cyan-600"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(Nr,{selectedChart:s,onChartChange:a})]}),e.jsxs(t.ScrollArea,{className:"flex-1 p-6",children:[e.jsx(Ir,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,onAliasTemplateChange:x,onValueAliasesChange:j}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Tr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(y=>y.card.dataSource);const{columns:o,isLoading:i}=Te(),u=a||o||[],c={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},h=y=>{const C=b=>{if(b.id===y){const w=u[0]||c;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...b,groups:b.groups.map(C)}};r(C(n))},d=y=>{const C=b=>{if(b.id===y){const w=u[0]||c;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(C)}};r(C(n))},x=(y,C)=>{const b=w=>w.id===y?{...w,conditions:w.conditions.filter(I=>I.id!==C)}:{...w,groups:w.groups.map(b)};r(b(n))},j=(y,C)=>{const b=w=>w.id===y?{...w,groups:w.groups.filter(I=>I.id!==C)}:{...w,groups:w.groups.map(b)};r(b(n))},p=(y,C,b,w)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===y?{...D,conditions:D.conditions.map(S=>S.id===C?{...S,[b]:w}:S)}:{...D,groups:D.groups.map(I)};r(I(n))},g=(y,C,b)=>{const w=I=>I.id===y?{...I,conditions:I.conditions.map(D=>D.id===C?{...D,...b}:D)}:{...I,groups:I.groups.map(w)};r(w(n))},m=(y,C)=>{const b=w=>w.id===y?{...w,logicalOperator:C}:{...w,groups:w.groups.map(b)};r(b(n))},v=(y,C)=>{const b=w=>w.id===y?{...w,negate:C}:{...w,groups:w.groups.map(b)};r(b(n))},f=(y,C,b)=>{const w=I=>I.id===y?{...I,conditions:t.arrayMove(I.conditions,C,b)}:{...I,groups:I.groups.map(w)};r(w(n))},k=(y,C,b)=>{const w=I=>I.id===y?{...I,groups:t.arrayMove(I.groups,C,b)}:{...I,groups:I.groups.map(w)};r(w(n))},T=y=>{if(!y||y.conditions.length===0&&y.groups.length===0)return"-- No filters defined";const C=w=>{let I="";typeof w.field=="object"?I=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:I=String(w.field);const D=w.operator;let S=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(w.field.dataType==="date")(typeof S=="string"||S instanceof Date)&&(S=`DATE('${S}')`);else if(["in","not in"].includes(w.operator)){let F=[];Array.isArray(S)?F=S.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof S=="string"?F=S.split(",").map(O=>{const A=O.trim();return w.field.dataType==="string"?`'${A}'`:A}):typeof S=="number"&&(F=[String(S)]),S=`(${F.join(", ")})`}switch(D){case"contains":return typeof S=="string"?`${I} LIKE '%${S.replace(/'/g,"")}'`:`${I} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${I} LIKE '${S.replace(/'/g,"")}%'`:`${I} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${I} LIKE '%${S.replace(/'/g,"")}'`:`${I} LIKE '%${String(S)}'`;default:return`${I} ${D} ${S}`}},b=w=>{const I=w.conditions.map(C),D=w.groups.map(A=>b(A)),S=[...I,...D].filter(Boolean);if(S.length===0)return"";const F=S.join(` ${w.logicalOperator} `),O=S.length>1?`(${F})`:F;return w.negate?`NOT ${O}`:O};return b(y)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:h,addGroup:d,removeCondition:x,removeGroup:j,updateCondition:p,updateConditionFields:g,updateGroupOperator:m,updateGroupNegate:v,reorderConditions:f,reorderGroups:k,generateSQLPreview:T,hasAnyFilters:E}}const Mr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(ut,{className:"h-3 w-3"});case"file":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},Ar=s=>{switch(s){case"table":return"Table";case"view":return"View";case"dataset":return"Dataset";case"file":return"File";default:return"Table"}},Lr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Or({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,l]=L.useState(!1),u=L.useMemo(()=>{const c={};return n.forEach(h=>{const d=Lr(h);c[d]||(c[d]={}),c[d][h.entityId]||(c[d][h.entityId]=[]),c[d][h.entityId].push(h)}),c},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"truncate text-sm",children:[s.entityName,".",s.name]})}):r,e.jsx(Zs,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(u).map(([c,h])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),c]}),children:Object.entries(h).map(([d,x])=>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:[Mr(x[0].entityType),e.jsx("span",{children:x[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Ar(x[0].entityType)})]}),x.map(j=>e.jsxs(t.CommandItem,{value:j.id,onSelect:()=>{a(j),l(!1)},className:"pl-6",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===j.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:j.label}),j.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:j.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:j.dataType}),j.description&&e.jsxs("span",{children:["• ",j.description]}),j.customFormat&&e.jsxs("span",{children:["• ",j.customFormat]})]})]})]},j.id))]},`${c}-${d}`))},c))})]})})]})}function At(s){var p;const a=t.useEditorStore(g=>g.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(g=>g.card.config),o=r==null?void 0:r.joinPlan,i={...s,label:"value",role:"groupby"},l={...s,role:"metric",label:"count",aggregate:"COUNT"},u={joinPlan:o,groupByColumns:[i],metricColumns:[l]},c=((p=a.dataSource)==null?void 0:p.connectionId)||a.connectionId,{data:h,isPending:d,error:x}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:c,cardConfig:u,cardDataSource:a.dataSource})}catch(g){console.log(s),console.error("error",g)}},enabled:!!c,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(g=>({label:g.value||"BLANK",value:g.value||"BLANK",count:g.count})),isPending:d,error:x}}function Fr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=re.useState(!1),{filterValues:u}=At(s),c=d=>{n(a.filter(x=>x!==d))},h=d=>{a.includes(d)?n(a.filter(x=>x!==d)):n([...a,d])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(d=>{const x=u.find(j=>j.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:j=>{j.key==="Enter"&&c(d)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),c(d)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},d)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:u.map(d=>e.jsxs(t.CommandItem,{onSelect:()=>h(d.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(d.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.count})]})]},d.value))})]})]})})]})})}const ws=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=ws(n)}),a};function zr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=At(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ce,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):u?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))})]})}const Br=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Rr=["=","!=","contains","startsWith","endsWith","in","not in"],Pr=["=","!=",">",">=","<","<=","in","not in"],Vr=["=","!="],qr=["=","!=",">",">=","<","<=","in","not in"];function _r(s){switch(s){case"string":return Rr;case"number":return Pr;case"boolean":return Vr;case"date":return qr;default:return Br}}function ks({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:h,listeners:d,setNodeRef:x,transform:j,transition:p,isDragging:g}=t.useSortable({id:s.id}),{isPending:m,error:v}=At(s.field),f={transform:t.CSS.Transform.toString(j),transition:p};return e.jsxs("div",{ref:x,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-gray-50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...d,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:k=>l(n,k),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Or,{value:s.field,onValueChange:k=>{c(n,s.id,{field:k,value:""})},availableFields:u,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:k=>{k==="in"||k==="not in"?c(n,s.id,{operator:k,value:[]}):c(n,s.id,{operator:k,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_r(t.getDataType(s.field.dataType)).map(k=>e.jsx(t.SelectItem,{value:k,children:k},k))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?m?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ce,{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(Fr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(k=>typeof k=="string")?s.value:[],onChange:k=>c(n,s.id,{value:k}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:k=>c(n,s.id,{value:k.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(zr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:k=>c(n,s.id,{value:k}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:k=>c(n,s.id,{value:k==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:k=>o(n,s.id,"value",k.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Gr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:h,onReorderGroups:d,onAddCondition:x,onAddGroup:j,availableFields:p,renderFilterGroup:g,updateConditionFields:m}){const{attributes:v,listeners:f,setNodeRef:k,transform:T,transition:E,isDragging:y}=t.useSortable({id:s.id}),C={transform:t.CSS.Transform.toString(T),transition:E},b=I=>{const{active:D,over:S}=I;if(S&&D.id!==S.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===S.id);F!==-1&&O!==-1&&h(s.id,F,O)}},w=I=>{const{active:D,over:S}=I;if(S&&D.id!==S.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===S.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:k,style:C,className:`rounded-lg ${a>0?"mt-2 border border-gray-200":""} ${y?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-gray-50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-gray-400"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:I=>r(s.id,I),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:b,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(ks,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:m},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(I=>g(I,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function $r({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:h,removeCondition:d,removeGroup:x,updateCondition:j,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:m,reorderConditions:v,reorderGroups:f,generateSQLPreview:k,hasAnyFilters:T,setCurrentFilters:E}=Tr({initialFilters:s,availableFields:a}),y=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[C,b]=L.useState(!1),w=(S,F,O)=>{const A=N=>N.id===S?{...N,conditions:N.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...N,groups:N.groups.map(A)};E(A(i))},I=(S,F=0,O)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:y,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:N,over:M}=A;if(M&&N.id!==M.id){const z=S.conditions.findIndex(q=>q.id===N.id),R=S.conditions.findIndex(q=>q.id===M.id);z!==-1&&R!==-1&&v(S.id,z,R)}},children:e.jsx(t.SortableContext,{items:S.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:S.conditions.map((A,N)=>e.jsx(ks,{condition:A,index:N,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:d,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:p},A.id))})}),e.jsx(t.DndContext,{sensors:y,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:N,over:M}=A;if(M&&N.id!==M.id){const z=S.groups.findIndex(q=>q.id===N.id),R=S.groups.findIndex(q=>q.id===M.id);z!==-1&&R!==-1&&f(S.id,z,R)}},children:e.jsx(t.SortableContext,{items:S.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:S.groups.map(A=>I(A,F+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>c(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Gr,{group:S,depth:F,parentGroupId:O,onUpdateGroupOperator:g,onUpdateGroupNegate:m,onRemoveGroup:x,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:d,onReorderConditions:v,onReorderGroups:f,onAddCondition:c,onAddGroup:h,availableFields:l,renderFilterGroup:I,updateConditionFields:p},S.id),D=ws(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[u?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..."})]}):I(i),e.jsx("div",{className:"mt-4 border-t border-gray-200 pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:C,onCheckedChange:S=>b(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),T&&e.jsxs("div",{className:"mt-4 border-t border-gray-200 pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-gray-700",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-gray-50 p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-gray-800",children:k(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),D>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(T?i:null),children:"Apply Filters"})]})]})}function Hr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:l}){const u=h=>{n(s,h),l(!1)},c=()=>{r(s),l(!1)};return e.jsx(t.Dialog,{open:i,onOpenChange:l,children:e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx($r,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Es(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Is(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Jr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){const[o,i]=L.useState(null),l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=L.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||a.find(p=>p.id===j)?"source":n("groupBy").find(p=>p.id===j)?"groupBy":n("metrics").find(p=>p.id===j)?"metrics":n("pivotBy").find(p=>p.id===j)?"pivotBy":n("sortBy").find(p=>p.id===j)?"sortBy":null,[a,n]),c=(j,p)=>{const g=Is(p,j),m=t.getDataType(j.dataType),v=m==="date",f={id:g,name:j.name,dataType:j.dataType,label:t.toLabel(j.name),qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType};if(p==="metrics"){const k=m==="number"?"SUM":"COUNT",T=Es(j.label,k);return{...f,role:"metric",label:T,aggregate:k}}return p==="groupBy"?{...f,role:"groupby",...v&&{granularity:"month"}}:p==="pivotBy"?{...f,role:"pivotby"}:p==="sortBy"?{...f,role:"sortby",direction:"asc"}:null},h=L.useCallback(j=>{i(j.active.id)},[]),d=L.useCallback(j=>{const{active:p,over:g}=j;if(!g||!s){i(null);return}const m=p.id,v=g.id,f=u(m),k=u(v)||v;if(f==="source"&&k!=="source"){const T=[...a].find(b=>b.id===m);if(!T){i(null);return}const E=n(k);if(E.some(b=>b.name===T.name&&b.qualifiedEntityName===T.qualifiedEntityName)){i(null);return}const C=c(T,k);i(null),r(k,[...E,C]);return}if(f&&k&&f!=="source"&&k!=="source"&&f!==k){const T=n(f),E=n(k),y=T.find(w=>w.id===m);if(!y){i(null);return}const C=c(y,k);i(null);const b=T.filter(w=>w.id!==m);r(f,b),r(k,[...E,C]);return}if(f&&k&&f===k&&f!=="source"){const T=n(f),E=T.findIndex(C=>C.id===m),y=T.findIndex(C=>C.id===v);if(E!==y){const C=t.arrayMove(T,E,y);r(f,C)}}i(null)},[s,a,n,r,u]),x=o?l.find(j=>j.id===o):null;return{activeId:o,activeField:x,handleDragStart:h,handleDragEnd:d}}const Ur=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:c,removeSortByColumn:h}=t.useEditorActions(),d=s==null?void 0:s.id,x=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,dateFormat:y.dateFormat,customFormat:y.customFormat,granularity:y.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,direction:y.direction}));case"source":return[];default:return[]}},[s]),j=L.useCallback((E,y)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:y});break}case"metrics":{a(d,{metricColumns:y});break}case"pivotBy":{a(d,{pivotByColumns:y});break}case"sortBy":{a(d,{sortByColumns:y});break}}},[d,a]),p=L.useCallback((E,y,C)=>{if(!d)return;const w=x(E)[y];if(w)switch(E){case"groupBy":n(d,w.id,{label:C});break;case"metrics":r(d,w.id,{label:C});break;case"pivotBy":o(d,w.id,{label:C});break;case"sortBy":i(d,w.id,{label:C});break}},[d,x,n,r,o,i]),g=L.useCallback((E,y)=>{if(!d)return;const b=x("metrics")[E];b&&r(d,b.id,{aggregate:y,label:Es(b.name,y)})},[d,x,r]),m=L.useCallback((E,y,C)=>{if(!d)return;const w=x("groupBy")[E];if(!w)return;const I={dateFormat:y};y==="custom"&&C?I.customFormat=C:I.customFormat=void 0,n(d,w.id,I)},[d,x,n]),v=L.useCallback((E,y)=>{if(!d)return;const b=x("groupBy")[E];b&&n(d,b.id,{granularity:y})},[d,x,n]),f=L.useCallback((E,y)=>{if(!d)return;const b=x("metrics")[E];b&&r(d,b.id,{aliasTemplate:y})},[d,x,r]),k=L.useCallback((E,y)=>{if(console.log("handleValueAliasesChange",E,y),!d)return;console.log("handleValueAliasesChange",E,y);const b=x("metrics")[E];b&&(console.log("handleValueAliasesChange",y),r(d,b.id,{valueAliases:y}))},[d,x,r]),T=L.useCallback((E,y)=>{if(!d)return;const b=x(E)[y];if(b)switch(E){case"groupBy":l(d,b.id);break;case"metrics":u(d,b.id);break;case"pivotBy":c(d,b.id);break;case"sortBy":h(d,b.id);break}},[d,x,l,u,c,h]);return{getFieldsForContainer:x,setFieldsForContainer:j,updateLabel:p,handleAggregationChange:g,handleDateFormatChange:m,handleGranularityChange:v,handleAliasTemplateChange:f,handleValueAliasesChange:k,removeField:T}};function Yr({activeView:s,onViewChange:a}){return e.jsx(t.Tabs,{value:s,onValueChange:n=>a(n),children:e.jsxs(t.TabsList,{className:"h-9 w-fit",children:[e.jsx(t.TabsTrigger,{value:"table",className:"text-xs",children:"Results"}),e.jsx(t.TabsTrigger,{value:"chart",className:"text-xs",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"sql",className:"text-xs",children:"SQL"})]})})}function Kr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:h,columns:d,columnsLoading:x,columnsError:j}){var b;const p=t.useEditorStore(w=>w.card),{updateCardConfig:g}=t.useEditorActions(),{data:m,errorMessage:v,isPending:f,isLoading:k,isFetching:T}=t.useDashboardCardQuery(h);function E(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:JSON.stringify(p.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:x?"Loading...":j?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const y=w=>{if(!p.config)return;if(!w.length){g(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,D=w.map(({id:S,desc:F})=>{var M,z;const O=(M=I.metricColumns)==null?void 0:M.find(R=>R.label===S),A=(z=I.groupByColumns)==null?void 0:z.find(R=>R.label===S),N=O||A;return N?{id:Is("sortBy",N),name:N.name,dataType:N.dataType,label:N.label,qualifiedEntityName:N.qualifiedEntityName,entityId:N.entityId,entityName:N.entityName,entityType:N.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(S=>S!==null);g(p.id,{...I,sortByColumns:D})},C=L.useMemo(()=>{var w,I;return(I=(w=p.config)==null?void 0:w.sortByColumns)==null?void 0:I.map(D=>({id:D.label,desc:D.direction==="desc"}))},[(b=p.config)==null?void 0:b.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c}),n&&E(),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsx(Yr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"gap-1",onClick:u,children:[e.jsx(ft,{className:"h-3.5 w-3.5"}),c>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:c})]}),e.jsx("div",{className:"flex grow items-center justify-end opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(ps,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:k||T?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ce,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(fs,{})}),s==="table"&&(m==null?void 0:m.records)&&e.jsx("div",{className:"flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(t.TableVisual,{card:h,data:m==null?void 0:m.records,onSortChange:y,sortState:C})}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[e.jsx("h3",{className:"mb-3 text-sm font-medium text-gray-700",children:"Generated SQL Query"}),e.jsx(os,{sql:m==null?void 0:m.sql,error:v})]})})]})]})]})}function Qr({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex 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(t.GripVertical,{className:"h-3 w-3 text-gray-400"}),e.jsx(Ss,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const Wr=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.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=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Xr(){var P,H;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),l=t.useEditorStore(Y=>Y.showAIDialog),{setCardType:u}=t.useEditorActions(),c=t.useEditorStore(Y=>Y.card.type);L.useEffect(()=>Wr(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},x=()=>{console.log("Advanced mode toggled")},j=()=>{i(!0)},p=Y=>{u(Y)},g=t.useEditorStore(Y=>Y.frame),m=t.useEditorStore(Y=>Y.card);t.useEditorStore(Y=>Y.activeTabCardId),t.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:v,removeCard:f,updateCard:k,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:y=[],isLoading:C,error:b}=Te(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=m,{getFieldsForContainer:D,setFieldsForContainer:S,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:N,handleAliasTemplateChange:M,handleValueAliasesChange:z,removeField:R}=Ur(I),{activeField:q,handleDragStart:B,handleDragEnd:K}=Jr({activeCardId:g.activeCardId,sourceFields:y,getFieldsForContainer:D,setFieldsForContainer:S}),J=(Y,Z)=>{Z&&E(Y,Z)},$=Y=>{var Z;k(Y,{config:{...(Z=g.cards.find(_=>_.id===Y))==null?void 0:Z.config,filters:void 0}})},U=y,G=Y=>{if(!Y)return 0;let Z=Y.conditions.length;return Y.groups.forEach(_=>{Z+=G(_)}),Z},V=G(((P=I==null?void 0:I.config)==null?void 0:P.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:B,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(vr,{}),!l&&e.jsx(Dr,{selectedChart:c,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:R,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:N,onAliasTemplateChange:M,onValueAliasesChange:z}),e.jsx(Kr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:d,onAdvancedToggle:x,onFiltersClick:j,filterCount:V,activeCard:I,dataSourceState:m.dataSource||t.EMPTY_DATA_SOURCE,columns:y,columnsLoading:C,columnsError:b,getFieldsForContainer:D,cards:g.cards,activeCardId:g.activeCardId,addCard:v,setActiveCard:T})]}),I&&e.jsx(Hr,{cardId:I.id,filters:((H=I.config)==null?void 0:H.filters)||null,onFiltersChange:J,onClearFilters:$,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Qr,{activeField:q||null})})]})}function Zr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(k=>k.showAIDialog),i=t.useEditorStore(k=>k.isDevMode),{setAuthToken:l}=t.useDashboardActions(),{setShowAIDialog:u,setOnSave:c,setOnClose:h}=t.useEditorActions(),{handleDragOver:d,handleDragEnd:x,handleDragStart:j,handleDragCancel:p,sensors:g}=Jn();L.useEffect(()=>{a&&c(a),n&&h(n)},[a,c,n,h]),L.useEffect(()=>{s&&s.accessToken&&l(s)},[s,l]),L.useEffect(()=>{var k,T;o?((k=r.current)==null||k.resize(40),u(!0)):(u(!1),(T=r.current)==null||T.resize(0))},[o,u]);function m(k){k<1?u(!1):o||u(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(rs,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(lr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:m,defaultSize:0,children:e.jsx(Gt,{})})]})]})}function f(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Xr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:m,defaultSize:0,children:e.jsx(Gt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:g,onDragStart:j,onDragEnd:x,onDragOver:d,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):f()})}function eo(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(l=>l.actions),n=t.useDashboardStore(l=>l.isVisualEditing),r=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){s&&(r(s,l),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Zr,{onSave:o,onClose:i})})}function to(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=vs();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const l=n==null?void 0:n.find(u=>u.column===t.fmt(i.column_name)&&u.table===a&&u.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.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":l}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function so(){t.useDashboardStore(a=>a.showFilters);const s=t.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(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(rs,{type:"filter",ColumnsComponent:()=>e.jsx(to,{})})})]})}function no(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.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(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function ao(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.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(no,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(so,{})})]})}function ro(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.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(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function oo({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(ro,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(qn,{}),e.jsx(eo,{}),e.jsx(ao,{})]})]})]})})}exports.DashboardPlus=oo;exports.ScheduleDashboard=ns;exports.SelectComponent=be;exports.cleanCard=es;exports.downloadPdf=ss;exports.getDashbaordStateWithoutData=Ct;
410
+ ON ${T}`}),m};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:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>i(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(yr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx($t,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx($t,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsxs(t.Button,{onClick:()=>i(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function vr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(d=>d.card.dataSource),{updateDataSource:i}=t.useEditorActions(),[l,u]=L.useState([]),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return L.useEffect(()=>{s&&u((o==null?void 0:o.selectedEntities)||[])},[s,o==null?void 0:o.selectedEntities]),e.jsxs("div",{className:"flex w-80 flex-col border-r bg-background",children:[e.jsxs("div",{className:"",children:[e.jsx("div",{className:t.cn("p-4",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4 text-gray-500"}):e.jsx(t.ChevronRight,{className:"h-4 w-4 text-gray-500"}),e.jsx(t.Database,{className:"h-5 w-5 text-cyan-600"}),e.jsx("h2",{className:"font-semibold text-gray-900",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-8",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-4 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((d,x)=>e.jsxs(t.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:[d.name,e.jsx("button",{onClick:g=>{g.stopPropagation();const p=h.selectedEntities.filter(j=>!(j.name===d.name&&j.type===d.type));u(p),i({...c,...o,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 text-red-500"})})]},`${d.type}-${d.name}-${x}`)),h.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})]}),e.jsx(br,{})]})]}),e.jsx(fr,{}),e.jsx(t.DataSourceDialog,{dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:h,fallbackDataSource:c})]})}const Cr=[{id:"table",icon:He,label:"Table"},{id:"bar",icon:Ge,label:"Bar Chart"},{id:"line",icon:$e,label:"Line Chart"},{id:"stackedBar",icon:dt,label:"Stacked Bar Chart"},{id:"stackedLine",icon:It,label:"Stacked Line Chart"},{id:"scatter",icon:xt,label:"Scatter Chart"},{id:"bubble",icon:kt,label:"Bubble Chart"},{id:"pie",icon:ht,label:"Pie Chart"},{id:"doughnut",icon:pt,label:"Doughnut Chart"},{id:"funnel",icon:Et,label:"Funnel Chart"},{id:"radar",icon:yt,label:"Radar Chart"},{id:"polarArea",icon:wt,label:"Polar Area Chart"},{id:"tornado",icon:vt,label:"Tornado Chart"},{id:"range",icon:mt,label:"Range Chart"},{id:"kpi",icon:Dt,label:"KPI"},{id:"text",icon:Jt,label:"Text"},{id:"map",icon:jt,label:"Map"},{id:"custom",icon:bt,label:"Custom"}];function Nr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(h){i(null),r({}),n(h),["kpi","custom","text","map"].includes(h)&&(o(!0),u(void 0)),a(h)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:Cr.map(h=>{const d=h.icon;return e.jsx(t.SelectItem,{value:h.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{children:h.label})]})},h.id)})})]})})}const Ss=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function Sr({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:l=>{r(l.target.value),i(!0)},onFocus:()=>i(!0),onClick:l=>l.stopPropagation(),className:"h-8 text-xs",onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):l.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function wr({aliasTemplate:s,onAliasTemplateChange:a}){var c;const[n,r]=L.useState(s),[o,i]=L.useState(!1),l=(c=t.useEditorStore(h=>{var d;return(d=h.card.config)==null?void 0:d.pivotByColumns}))==null?void 0:c[0],u=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.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(t.Input$1,{placeholder:u,value:o?n:s,onChange:h=>{r(h.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&o&&n!==s?(a(n),i(!1)):h.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function kr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},h=x=>{const g={...s};delete g[x],a(g)},d=x=>{const g={...s};delete g[x],g[o]=l,a(g),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,g],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?d(x):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:l,onChange:j=>u(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?d(x):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>d(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),u(g)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),u(g)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:c,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Er({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,hasPivotColumns:x=!1}){const{attributes:g,listeners:p,setNodeRef:j,transform:m,transition:v,isDragging:f}=t.useSortable({id:s.id}),[k,T]=L.useState(!1),[E,y]=L.useState(s.dateFormat||"YYYY-MM-DD"),[C,b]=L.useState(s.customFormat||""),[w,I]=L.useState(!!s.customFormat),[D,S]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,N]=L.useState(s.valueAliases||{}),M=_=>{_==="custom"?I(!0):(I(!1),y(_),a==="groupBy"&&h&&h(_,""))},z=_=>{b(_),a==="groupBy"&&h&&h("custom",_)},R=_=>{S(_),a==="groupBy"&&d&&d(_)},q=_=>{O(_),l&&l(_)},B=_=>{N(_),u&&u(_)},K={transform:t.CSS.Transform.toString(m),transition:v},J=t.getDataType(s.dataType),$=J==="date",Y=[{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..."}];return e.jsxs("div",{ref:j,style:K,...g,...p,className:`group flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(Ss,{dataType:J}),e.jsx("span",{className:"max-w-[180px] flex-1 overflow-hidden truncate text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:_=>{_.stopPropagation(),T(!k)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${k?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:_=>{_.stopPropagation(),console.log("DraggableField - Current sortDirection:",o);const V=o==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",V),i(V)},children:o==="asc"?e.jsx(_e,{className:"h-3 w-3"}):e.jsx(qe,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:_=>{_.stopPropagation(),n()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),k&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("span",{className:"flex-1 overflow-hidden truncate px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),a!=="pivotBy"&&e.jsx(Sr,{label:s.label??"",onLabelChange:r}),$&&a!=="groupBy"&&e.jsx("div",{className:"space-y-1",children:e.jsxs(t.Select,{defaultValue:"day",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})}),$&&a==="groupBy"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Granularity"}),e.jsxs(t.Select,{value:D,onValueChange:R,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Date Format"}),e.jsxs(t.Select,{value:w?"custom":E,onValueChange:M,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:Y.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))})]}),w&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:C,onChange:_=>{_.stopPropagation(),z(_.target.value)},onClick:_=>_.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),a==="metrics"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:_=>{c&&c(_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),x&&e.jsxs(e.Fragment,{children:[e.jsx(wr,{aliasTemplate:F,onAliasTemplateChange:q}),e.jsx(kr,{valueAliases:A,onValueAliasesChange:B})]})]})]})]})}function Fe({zone:s,fields:a,label:n,placeholder:r,onRemove:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:h,onValueAliasesChange:d,shouldShow:x,hasPivotColumns:g=!1}){const{isOver:p,setNodeRef:j}=t.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),v=t.useEditorStore(T=>T.card),f=a.length>0,k=(T,E)=>{var C;!((C=v.config)!=null&&C.sortByColumns)||v.config.sortByColumns.findIndex(b=>b.id===T)===-1||m(v.id,T,{direction:E})};return s==="sortBy"&&x===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsx(t.Label,{className:"mb-2 block text-sm font-medium",children:n}),e.jsx("div",{ref:j,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${p?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((T,E)=>{const C=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Er,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:b=>i(E,b),sortDirection:C,onSortDirectionChange:b=>k(T.id,b),onAggregationChange:l?b=>l(E,b):void 0,onAliasTemplateChange:h?b=>h(E,b):void 0,onValueAliasesChange:d?b=>d(E,b):void 0,onDateFormatChange:u?(b,w)=>u(E,b,w):void 0,onGranularityChange:c?b=>c(E,b):void 0,hasPivotColumns:g})})},T.id)})})})})]})}function Ir({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,onRemoveField:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:h,onValueAliasesChange:d}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:s,label:"Group By",placeholder:"Drop fields to group data",onRemove:x=>o("groupBy",x),onLabelChange:(x,g)=>i("groupBy",x,g),onDateFormatChange:(x,g,p)=>u&&u(x,g,p),onGranularityChange:(x,g)=>c&&c(x,g)}),e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Pivot By",placeholder:"Drop fields to pivot data",onRemove:x=>o("pivotBy",x),onLabelChange:(x,g)=>i("pivotBy",x,g)}),e.jsx(Fe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:x=>o("metrics",x),onLabelChange:(x,g)=>i("metrics",x,g),onAggregationChange:l,onAliasTemplateChange:h,onValueAliasesChange:d,hasPivotColumns:a.length>0}),r&&r.length>0&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields to sort data",onRemove:x=>o("sortBy",x),onLabelChange:(x,g)=>i("sortBy",x,g),shouldShow:s.length>0||a.length>0||n.length>0})]})}function Dr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,onAliasTemplateChange:x,onValueAliasesChange:g}){t.useEditorStore(j=>j.showAIDialog);const{setShowAIDialog:p}=t.useEditorActions();return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-5 w-5 text-cyan-600"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(Nr,{selectedChart:s,onChartChange:a})]}),e.jsxs(t.ScrollArea,{className:"flex-1 p-6",children:[e.jsx(Ir,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,onAliasTemplateChange:x,onValueAliasesChange:g}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Tr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(y=>y.card.dataSource);const{columns:o,isLoading:i}=Me(),u=a||o||[],c={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},h=y=>{const C=b=>{if(b.id===y){const w=u[0]||c;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...b,groups:b.groups.map(C)}};r(C(n))},d=y=>{const C=b=>{if(b.id===y){const w=u[0]||c;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(C)}};r(C(n))},x=(y,C)=>{const b=w=>w.id===y?{...w,conditions:w.conditions.filter(I=>I.id!==C)}:{...w,groups:w.groups.map(b)};r(b(n))},g=(y,C)=>{const b=w=>w.id===y?{...w,groups:w.groups.filter(I=>I.id!==C)}:{...w,groups:w.groups.map(b)};r(b(n))},p=(y,C,b,w)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===y?{...D,conditions:D.conditions.map(S=>S.id===C?{...S,[b]:w}:S)}:{...D,groups:D.groups.map(I)};r(I(n))},j=(y,C,b)=>{const w=I=>I.id===y?{...I,conditions:I.conditions.map(D=>D.id===C?{...D,...b}:D)}:{...I,groups:I.groups.map(w)};r(w(n))},m=(y,C)=>{const b=w=>w.id===y?{...w,logicalOperator:C}:{...w,groups:w.groups.map(b)};r(b(n))},v=(y,C)=>{const b=w=>w.id===y?{...w,negate:C}:{...w,groups:w.groups.map(b)};r(b(n))},f=(y,C,b)=>{const w=I=>I.id===y?{...I,conditions:t.arrayMove(I.conditions,C,b)}:{...I,groups:I.groups.map(w)};r(w(n))},k=(y,C,b)=>{const w=I=>I.id===y?{...I,groups:t.arrayMove(I.groups,C,b)}:{...I,groups:I.groups.map(w)};r(w(n))},T=y=>{if(!y||y.conditions.length===0&&y.groups.length===0)return"-- No filters defined";const C=w=>{let I="";typeof w.field=="object"?I=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:I=String(w.field);const D=w.operator;let S=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(w.field.dataType==="date")(typeof S=="string"||S instanceof Date)&&(S=`DATE('${S}')`);else if(["in","not in"].includes(w.operator)){let F=[];Array.isArray(S)?F=S.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof S=="string"?F=S.split(",").map(O=>{const A=O.trim();return w.field.dataType==="string"?`'${A}'`:A}):typeof S=="number"&&(F=[String(S)]),S=`(${F.join(", ")})`}switch(D){case"contains":return typeof S=="string"?`${I} LIKE '%${S.replace(/'/g,"")}'`:`${I} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${I} LIKE '${S.replace(/'/g,"")}%'`:`${I} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${I} LIKE '%${S.replace(/'/g,"")}'`:`${I} LIKE '%${String(S)}'`;default:return`${I} ${D} ${S}`}},b=w=>{const I=w.conditions.map(C),D=w.groups.map(A=>b(A)),S=[...I,...D].filter(Boolean);if(S.length===0)return"";const F=S.join(` ${w.logicalOperator} `),O=S.length>1?`(${F})`:F;return w.negate?`NOT ${O}`:O};return b(y)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:h,addGroup:d,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:j,updateGroupOperator:m,updateGroupNegate:v,reorderConditions:f,reorderGroups:k,generateSQLPreview:T,hasAnyFilters:E}}const Mr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(ut,{className:"h-3 w-3"});case"file":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},Ar=s=>{switch(s){case"table":return"Table";case"view":return"View";case"dataset":return"Dataset";case"file":return"File";default:return"Table"}},Lr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Or({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,l]=L.useState(!1),u=L.useMemo(()=>{const c={};return n.forEach(h=>{const d=Lr(h);c[d]||(c[d]={}),c[d][h.entityId]||(c[d][h.entityId]=[]),c[d][h.entityId].push(h)}),c},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"truncate text-sm",children:[s.entityName,".",s.name]})}):r,e.jsx(Zs,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(u).map(([c,h])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),c]}),children:Object.entries(h).map(([d,x])=>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:[Mr(x[0].entityType),e.jsx("span",{children:x[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Ar(x[0].entityType)})]}),x.map(g=>e.jsxs(t.CommandItem,{value:g.id,onSelect:()=>{a(g),l(!1)},className:"pl-6",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===g.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:g.label}),g.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:g.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:g.dataType}),g.description&&e.jsxs("span",{children:["• ",g.description]}),g.customFormat&&e.jsxs("span",{children:["• ",g.customFormat]})]})]})]},g.id))]},`${c}-${d}`))},c))})]})})]})}function At(s){var p;const a=t.useEditorStore(j=>j.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(j=>j.card.config),o=r==null?void 0:r.joinPlan,i={...s,label:"value",role:"groupby"},l={...s,role:"metric",label:"count",aggregate:"COUNT"},u={joinPlan:o,groupByColumns:[i],metricColumns:[l]},c=((p=a.dataSource)==null?void 0:p.connectionId)||a.connectionId,{data:h,isPending:d,error:x}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:c,cardConfig:u,cardDataSource:a.dataSource})}catch(j){console.log(s),console.error("error",j)}},enabled:!!c,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:j.count})),isPending:d,error:x}}function Fr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=re.useState(!1),{filterValues:u}=At(s),c=d=>{n(a.filter(x=>x!==d))},h=d=>{a.includes(d)?n(a.filter(x=>x!==d)):n([...a,d])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(d=>{const x=u.find(g=>g.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:g=>{g.key==="Enter"&&c(d)},onMouseDown:g=>{g.preventDefault(),g.stopPropagation()},onClick:g=>{g.stopPropagation(),c(d)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},d)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:u.map(d=>e.jsxs(t.CommandItem,{onSelect:()=>h(d.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(d.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.count})]})]},d.value))})]})]})})]})})}const ws=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=ws(n)}),a};function zr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=At(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ce,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):u?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))})]})}const Br=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Rr=["=","!=","contains","startsWith","endsWith","in","not in"],Pr=["=","!=",">",">=","<","<=","in","not in"],Vr=["=","!="],qr=["=","!=",">",">=","<","<=","in","not in"];function _r(s){switch(s){case"string":return Rr;case"number":return Pr;case"boolean":return Vr;case"date":return qr;default:return Br}}function ks({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:h,listeners:d,setNodeRef:x,transform:g,transition:p,isDragging:j}=t.useSortable({id:s.id}),{isPending:m,error:v}=At(s.field),f={transform:t.CSS.Transform.toString(g),transition:p};return e.jsxs("div",{ref:x,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-gray-50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...d,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:k=>l(n,k),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Or,{value:s.field,onValueChange:k=>{c(n,s.id,{field:k,value:""})},availableFields:u,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:k=>{k==="in"||k==="not in"?c(n,s.id,{operator:k,value:[]}):c(n,s.id,{operator:k,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_r(t.getDataType(s.field.dataType)).map(k=>e.jsx(t.SelectItem,{value:k,children:k},k))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?m?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ce,{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(Fr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(k=>typeof k=="string")?s.value:[],onChange:k=>c(n,s.id,{value:k}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:k=>c(n,s.id,{value:k.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(zr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:k=>c(n,s.id,{value:k}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:k=>c(n,s.id,{value:k==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:k=>o(n,s.id,"value",k.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Gr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:h,onReorderGroups:d,onAddCondition:x,onAddGroup:g,availableFields:p,renderFilterGroup:j,updateConditionFields:m}){const{attributes:v,listeners:f,setNodeRef:k,transform:T,transition:E,isDragging:y}=t.useSortable({id:s.id}),C={transform:t.CSS.Transform.toString(T),transition:E},b=I=>{const{active:D,over:S}=I;if(S&&D.id!==S.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===S.id);F!==-1&&O!==-1&&h(s.id,F,O)}},w=I=>{const{active:D,over:S}=I;if(S&&D.id!==S.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===S.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:k,style:C,className:`rounded-lg ${a>0?"mt-2 border border-gray-200":""} ${y?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-gray-50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-gray-400"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:I=>r(s.id,I),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:b,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(ks,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:m},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(I=>j(I,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>g(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function $r({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:h,removeCondition:d,removeGroup:x,updateCondition:g,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:m,reorderConditions:v,reorderGroups:f,generateSQLPreview:k,hasAnyFilters:T,setCurrentFilters:E}=Tr({initialFilters:s,availableFields:a}),y=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[C,b]=L.useState(!1),w=(S,F,O)=>{const A=N=>N.id===S?{...N,conditions:N.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...N,groups:N.groups.map(A)};E(A(i))},I=(S,F=0,O)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:y,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:N,over:M}=A;if(M&&N.id!==M.id){const z=S.conditions.findIndex(q=>q.id===N.id),R=S.conditions.findIndex(q=>q.id===M.id);z!==-1&&R!==-1&&v(S.id,z,R)}},children:e.jsx(t.SortableContext,{items:S.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:S.conditions.map((A,N)=>e.jsx(ks,{condition:A,index:N,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:g,onUpdateField:w,onRemoveCondition:d,onUpdateGroupOperator:j,availableFields:l,updateConditionFields:p},A.id))})}),e.jsx(t.DndContext,{sensors:y,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:N,over:M}=A;if(M&&N.id!==M.id){const z=S.groups.findIndex(q=>q.id===N.id),R=S.groups.findIndex(q=>q.id===M.id);z!==-1&&R!==-1&&f(S.id,z,R)}},children:e.jsx(t.SortableContext,{items:S.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:S.groups.map(A=>I(A,F+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>c(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(S.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Gr,{group:S,depth:F,parentGroupId:O,onUpdateGroupOperator:j,onUpdateGroupNegate:m,onRemoveGroup:x,onUpdateCondition:g,onUpdateField:w,onRemoveCondition:d,onReorderConditions:v,onReorderGroups:f,onAddCondition:c,onAddGroup:h,availableFields:l,renderFilterGroup:I,updateConditionFields:p},S.id),D=ws(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[u?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..."})]}):I(i),e.jsx("div",{className:"mt-4 border-t border-gray-200 pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:C,onCheckedChange:S=>b(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),T&&e.jsxs("div",{className:"mt-4 border-t border-gray-200 pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-gray-700",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-gray-50 p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-gray-800",children:k(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),D>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(T?i:null),children:"Apply Filters"})]})]})}function Hr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:l}){const u=h=>{n(s,h),l(!1)},c=()=>{r(s),l(!1)};return e.jsx(t.Dialog,{open:i,onOpenChange:l,children:e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx($r,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Es(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Is(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Jr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){const[o,i]=L.useState(null),l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=L.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]),c=(g,p)=>{const j=Is(p,g),m=t.getDataType(g.dataType),v=m==="date",f={id:j,name:g.name,dataType:g.dataType,label:t.toLabel(g.name),qualifiedEntityName:g.qualifiedEntityName,entityId:g.entityId,entityName:g.entityName,entityType:g.entityType};if(p==="metrics"){const k=m==="number"?"SUM":"COUNT",T=Es(g.label,k);return{...f,role:"metric",label:T,aggregate:k}}return p==="groupBy"?{...f,role:"groupby",...v&&{granularity:"month"}}:p==="pivotBy"?{...f,role:"pivotby"}:p==="sortBy"?{...f,role:"sortby",direction:"asc"}:null},h=L.useCallback(g=>{i(g.active.id)},[]),d=L.useCallback(g=>{const{active:p,over:j}=g;if(!j||!s){i(null);return}const m=p.id,v=j.id,f=u(m),k=u(v)||v;if(f==="source"&&k!=="source"){const T=[...a].find(b=>b.id===m);if(!T){i(null);return}const E=n(k);if(E.some(b=>b.name===T.name&&b.qualifiedEntityName===T.qualifiedEntityName)){i(null);return}const C=c(T,k);i(null),r(k,[...E,C]);return}if(f&&k&&f!=="source"&&k!=="source"&&f!==k){const T=n(f),E=n(k),y=T.find(w=>w.id===m);if(!y){i(null);return}const C=c(y,k);i(null);const b=T.filter(w=>w.id!==m);r(f,b),r(k,[...E,C]);return}if(f&&k&&f===k&&f!=="source"){const T=n(f),E=T.findIndex(C=>C.id===m),y=T.findIndex(C=>C.id===v);if(E!==y){const C=t.arrayMove(T,E,y);r(f,C)}}i(null)},[s,a,n,r,u]),x=o?l.find(g=>g.id===o):null;return{activeId:o,activeField:x,handleDragStart:h,handleDragEnd:d}}const Ur=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:c,removeSortByColumn:h}=t.useEditorActions(),d=s==null?void 0:s.id,x=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,dateFormat:y.dateFormat,customFormat:y.customFormat,granularity:y.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,direction:y.direction}));case"source":return[];default:return[]}},[s]),g=L.useCallback((E,y)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:y});break}case"metrics":{a(d,{metricColumns:y});break}case"pivotBy":{a(d,{pivotByColumns:y});break}case"sortBy":{a(d,{sortByColumns:y});break}}},[d,a]),p=L.useCallback((E,y,C)=>{if(!d)return;const w=x(E)[y];if(w)switch(E){case"groupBy":n(d,w.id,{label:C});break;case"metrics":r(d,w.id,{label:C});break;case"pivotBy":o(d,w.id,{label:C});break;case"sortBy":i(d,w.id,{label:C});break}},[d,x,n,r,o,i]),j=L.useCallback((E,y)=>{if(!d)return;const b=x("metrics")[E];b&&r(d,b.id,{aggregate:y,label:Es(b.name,y)})},[d,x,r]),m=L.useCallback((E,y,C)=>{if(!d)return;const w=x("groupBy")[E];if(!w)return;const I={dateFormat:y};y==="custom"&&C?I.customFormat=C:I.customFormat=void 0,n(d,w.id,I)},[d,x,n]),v=L.useCallback((E,y)=>{if(!d)return;const b=x("groupBy")[E];b&&n(d,b.id,{granularity:y})},[d,x,n]),f=L.useCallback((E,y)=>{if(!d)return;const b=x("metrics")[E];b&&r(d,b.id,{aliasTemplate:y})},[d,x,r]),k=L.useCallback((E,y)=>{if(console.log("handleValueAliasesChange",E,y),!d)return;console.log("handleValueAliasesChange",E,y);const b=x("metrics")[E];b&&(console.log("handleValueAliasesChange",y),r(d,b.id,{valueAliases:y}))},[d,x,r]),T=L.useCallback((E,y)=>{if(!d)return;const b=x(E)[y];if(b)switch(E){case"groupBy":l(d,b.id);break;case"metrics":u(d,b.id);break;case"pivotBy":c(d,b.id);break;case"sortBy":h(d,b.id);break}},[d,x,l,u,c,h]);return{getFieldsForContainer:x,setFieldsForContainer:g,updateLabel:p,handleAggregationChange:j,handleDateFormatChange:m,handleGranularityChange:v,handleAliasTemplateChange:f,handleValueAliasesChange:k,removeField:T}};function Yr({activeView:s,onViewChange:a}){return e.jsx(t.Tabs,{value:s,onValueChange:n=>a(n),children:e.jsxs(t.TabsList,{className:"h-9 w-fit",children:[e.jsx(t.TabsTrigger,{value:"table",className:"text-xs",children:"Results"}),e.jsx(t.TabsTrigger,{value:"chart",className:"text-xs",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"sql",className:"text-xs",children:"SQL"})]})})}function Kr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:h,columns:d,columnsLoading:x,columnsError:g}){var b;const p=t.useEditorStore(w=>w.card),{updateCardConfig:j}=t.useEditorActions(),{data:m,errorMessage:v,isPending:f,isLoading:k,isFetching:T}=t.useDashboardCardQuery(h);function E(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:JSON.stringify(p.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium text-gray-700",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs text-gray-800",children:x?"Loading...":g?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const y=w=>{if(!p.config)return;if(!w.length){j(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,D=w.map(({id:S,desc:F})=>{var M,z;const O=(M=I.metricColumns)==null?void 0:M.find(R=>R.label===S),A=(z=I.groupByColumns)==null?void 0:z.find(R=>R.label===S),N=O||A;return N?{id:Is("sortBy",N),name:N.name,dataType:N.dataType,label:N.label,qualifiedEntityName:N.qualifiedEntityName,entityId:N.entityId,entityName:N.entityName,entityType:N.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(S=>S!==null);j(p.id,{...I,sortByColumns:D})},C=L.useMemo(()=>{var w,I;return(I=(w=p.config)==null?void 0:w.sortByColumns)==null?void 0:I.map(D=>({id:D.label,desc:D.direction==="desc"}))},[(b=p.config)==null?void 0:b.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c}),n&&E(),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsx(Yr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"gap-1",onClick:u,children:[e.jsx(ft,{className:"h-3.5 w-3.5"}),c>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:c})]}),e.jsx("div",{className:"flex grow items-center justify-end opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(ps,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:k||T?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ce,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(fs,{})}),s==="table"&&(m==null?void 0:m.records)&&e.jsx("div",{className:"flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(t.TableVisual,{card:h,data:m==null?void 0:m.records,onSortChange:y,sortState:C})}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[e.jsx("h3",{className:"mb-3 text-sm font-medium text-gray-700",children:"Generated SQL Query"}),e.jsx(os,{sql:m==null?void 0:m.sql,error:v})]})})]})]})]})}function Qr({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex 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(t.GripVertical,{className:"h-3 w-3 text-gray-400"}),e.jsx(Ss,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const Wr=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.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=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Xr(){var P,H;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),l=t.useEditorStore(U=>U.showAIDialog),{setCardType:u}=t.useEditorActions(),c=t.useEditorStore(U=>U.card.type);L.useEffect(()=>Wr(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},x=()=>{console.log("Advanced mode toggled")},g=()=>{i(!0)},p=U=>{u(U)},j=t.useEditorStore(U=>U.frame),m=t.useEditorStore(U=>U.card);t.useEditorStore(U=>U.activeTabCardId),t.useEditorStore(U=>U.actions.getAvailableFields);const{addCard:v,removeCard:f,updateCard:k,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:y=[],isLoading:C,error:b}=Me(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=m,{getFieldsForContainer:D,setFieldsForContainer:S,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:N,handleAliasTemplateChange:M,handleValueAliasesChange:z,removeField:R}=Ur(I),{activeField:q,handleDragStart:B,handleDragEnd:K}=Jr({activeCardId:j.activeCardId,sourceFields:y,getFieldsForContainer:D,setFieldsForContainer:S}),J=(U,Z)=>{Z&&E(U,Z)},$=U=>{var Z;k(U,{config:{...(Z=j.cards.find(de=>de.id===U))==null?void 0:Z.config,filters:void 0}})},Y=y,_=U=>{if(!U)return 0;let Z=U.conditions.length;return U.groups.forEach(de=>{Z+=_(de)}),Z},V=_(((P=I==null?void 0:I.config)==null?void 0:P.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:B,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(vr,{}),!l&&e.jsx(Dr,{selectedChart:c,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:R,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:N,onAliasTemplateChange:M,onValueAliasesChange:z}),e.jsx(Kr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:d,onAdvancedToggle:x,onFiltersClick:g,filterCount:V,activeCard:I,dataSourceState:m.dataSource||t.EMPTY_DATA_SOURCE,columns:y,columnsLoading:C,columnsError:b,getFieldsForContainer:D,cards:j.cards,activeCardId:j.activeCardId,addCard:v,setActiveCard:T})]}),I&&e.jsx(Hr,{cardId:I.id,filters:((H=I.config)==null?void 0:H.filters)||null,onFiltersChange:J,onClearFilters:$,availableFields:Y,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Qr,{activeField:q||null})})]})}function Zr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(k=>k.showAIDialog),i=t.useEditorStore(k=>k.isDevMode),{setAuthToken:l}=t.useDashboardActions(),{setShowAIDialog:u,setOnSave:c,setOnClose:h}=t.useEditorActions(),{handleDragOver:d,handleDragEnd:x,handleDragStart:g,handleDragCancel:p,sensors:j}=Jn();L.useEffect(()=>{a&&c(a),n&&h(n)},[a,c,n,h]),L.useEffect(()=>{s&&s.accessToken&&l(s)},[s,l]),L.useEffect(()=>{var k,T;o?((k=r.current)==null||k.resize(40),u(!0)):(u(!1),(T=r.current)==null||T.resize(0))},[o,u]);function m(k){k<1?u(!1):o||u(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(rs,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(lr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:m,defaultSize:0,children:e.jsx(Gt,{})})]})]})}function f(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Xr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:m,defaultSize:0,children:e.jsx(Gt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:j,onDragStart:g,onDragEnd:x,onDragOver:d,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):f()})}function eo(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(l=>l.actions),n=t.useDashboardStore(l=>l.isVisualEditing),r=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){s&&(r(s,l),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Zr,{onSave:o,onClose:i})})}function to(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=vs();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const l=n==null?void 0:n.find(u=>u.column===t.fmt(i.column_name)&&u.table===a&&u.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.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":l}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function so(){t.useDashboardStore(a=>a.showFilters);const s=t.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(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(rs,{type:"filter",ColumnsComponent:()=>e.jsx(to,{})})})]})}function no(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.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(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function ao(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.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(no,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(so,{})})]})}function ro(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.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(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function oo({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(ro,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(qn,{}),e.jsx(eo,{}),e.jsx(ao,{})]})]})]})})}exports.DashboardPlus=oo;exports.ScheduleDashboard=ns;exports.SelectComponent=ve;exports.cleanCard=es;exports.downloadPdf=ss;exports.getDashbaordStateWithoutData=Ct;