react-semaphor 0.0.505 → 0.0.507

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 Ft=s=>{throw TypeError(s)};var Je=(s,a,n)=>a.has(s)||Ft("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)?Ft("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-DiwXdNV5.js"),L=require("react");require("react-dom");function Fs(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=Fs(L);function Bt(s,a){return s.filter(n=>!a.includes(n))}function Bs(s,a,n){const r=s.slice(0);return r[a]=n,r}var pe,ne,Ne,Ce,ae,he,Ie,De,Te,ee,tt,st,nt,at,rt,Jt,zs=(Jt=class extends t.Subscribable{constructor(a,n,r){super();oe(this,ee);oe(this,pe);oe(this,ne);oe(this,Ne);oe(this,Ce);oe(this,ae);oe(this,he);oe(this,Ie);oe(this,De);oe(this,Te,[]);te(this,pe,a),te(this,Ce,r),te(this,Ne,[]),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,Ne,a),te(this,Ce,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,Ne));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()&&(Bt(o,l).forEach(h=>{h.destroy()}),Bt(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,Ne=new WeakMap,Ce=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,Bs(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,Ce))==null?void 0:a.combine);n!==o&&t.notifyManager.batch(()=>{this.listeners.forEach(i=>{i(W(this,ne))})})}},Jt);function Rs({queries:s,...a},n){const r=t.useQueryClient(),o=t.useIsRestoring(),i=t.useQueryErrorResetBoundary(),l=re.useMemo(()=>s.map(x=>{const v=r.defaultQueryOptions(x);return v._optimisticResults=o?"isRestoring":"optimistic",v}),[s,r,o]);l.forEach(x=>{t.ensureSuspenseTimers(x),t.ensurePreventErrorBoundaryRetry(x,i)}),t.useClearResetErrorBoundary(i);const[u]=re.useState(()=>new zs(r,l,a)),[c,h,d]=u.getOptimisticResult(l,a.combine),m=!o&&a.subscribed!==!1;re.useSyncExternalStore(re.useCallback(x=>m?u.subscribe(t.notifyManager.batchCalls(x)):t.noop,[u,m]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),re.useEffect(()=>{u.setQueries(l,a,{listeners:!1})},[l,a,u]);const f=c.some((x,v)=>t.shouldSuspend(l[v],x))?c.flatMap((x,v)=>{const p=l[v];if(p){const k=new t.QueryObserver(r,p);if(t.shouldSuspend(p,x))return t.fetchOptimistic(p,k,i);t.willFetch(x,o)&&t.fetchOptimistic(p,k,i)}return[]}):[];if(f.length>0)throw Promise.all(f);const g=c.find((x,v)=>{const p=l[v];return p&&t.getHasError({result:x,errorResetBoundary:i,throwOnError:p.throwOnError,query:r.getQueryCache().get(p.queryHash),suspense:p.suspense})});if(g!=null&&g.error)throw g.error;return h(d())}/**
1
+ "use strict";var Ft=s=>{throw TypeError(s)};var Je=(s,a,n)=>a.has(s)||Ft("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)?Ft("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-B6aFim6x.js"),L=require("react");require("react-dom");function Fs(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=Fs(L);function Bt(s,a){return s.filter(n=>!a.includes(n))}function Bs(s,a,n){const r=s.slice(0);return r[a]=n,r}var pe,ne,Ne,Ce,ae,he,Ie,De,Te,ee,tt,st,nt,at,rt,Jt,zs=(Jt=class extends t.Subscribable{constructor(a,n,r){super();oe(this,ee);oe(this,pe);oe(this,ne);oe(this,Ne);oe(this,Ce);oe(this,ae);oe(this,he);oe(this,Ie);oe(this,De);oe(this,Te,[]);te(this,pe,a),te(this,Ce,r),te(this,Ne,[]),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,Ne,a),te(this,Ce,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,Ne));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()&&(Bt(o,l).forEach(h=>{h.destroy()}),Bt(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,Ne=new WeakMap,Ce=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,Bs(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,Ce))==null?void 0:a.combine);n!==o&&t.notifyManager.batch(()=>{this.listeners.forEach(i=>{i(W(this,ne))})})}},Jt);function Rs({queries:s,...a},n){const r=t.useQueryClient(),o=t.useIsRestoring(),i=t.useQueryErrorResetBoundary(),l=re.useMemo(()=>s.map(x=>{const v=r.defaultQueryOptions(x);return v._optimisticResults=o?"isRestoring":"optimistic",v}),[s,r,o]);l.forEach(x=>{t.ensureSuspenseTimers(x),t.ensurePreventErrorBoundaryRetry(x,i)}),t.useClearResetErrorBoundary(i);const[u]=re.useState(()=>new zs(r,l,a)),[c,h,d]=u.getOptimisticResult(l,a.combine),m=!o&&a.subscribed!==!1;re.useSyncExternalStore(re.useCallback(x=>m?u.subscribe(t.notifyManager.batchCalls(x)):t.noop,[u,m]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),re.useEffect(()=>{u.setQueries(l,a,{listeners:!1})},[l,a,u]);const f=c.some((x,v)=>t.shouldSuspend(l[v],x))?c.flatMap((x,v)=>{const p=l[v];if(p){const k=new t.QueryObserver(r,p);if(t.shouldSuspend(p,x))return t.fetchOptimistic(p,k,i);t.willFetch(x,o)&&t.fetchOptimistic(p,k,i)}return[]}):[];if(f.length>0)throw Promise.all(f);const g=c.find((x,v)=>{const p=l[v];return p&&t.getHasError({result:x,errorResetBoundary:i,throwOnError:p.throwOnError,query:r.getQueryCache().get(p.queryHash),suspense:p.suspense})});if(g!=null&&g.error)throw g.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.
@@ -402,4 +402,4 @@ ${I.joinType} JOIN ${D.name}
402
402
  ON ${F}`}),S},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(C=>!C.source.name||!C.target.name||!C.operator))))}}function gr({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(C=>C.card.config);const{columnGroups:l}=Me(),{joinPlan:u,expandedJoins:c,setJoinPlan:h,addJoin:d,removeJoin:m,updateJoin:N,moveJoinUp:f,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:p,addJoinKeyGroup:k,updateGroupOperator:T,removeJoinKeyGroup:E,addJoinKey:j,updateJoinKey:b,removeJoinKey:y,generateSQLPreview:S,isValidConfiguration:I}=fr({initialJoinPlan:s,availableDataSources:a}),D=C=>{const F=l.find(O=>O.entityName===C);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:C=>{const F=a.find(O=>O.name===C);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:C,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(C=>e.jsx(t.SelectItem,{value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},C.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:S()})]}),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-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:u.joins.map(C=>{const F=a.find(w=>w.name===C.source.name),O=a.find(w=>w.name===C.target.name),A=c.has(C.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:C.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",C.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:()=>f(C.id),disabled:C.sequence===1,children:e.jsx(_e,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>g(C.id),disabled:C.sequence===u.joins.length,children:e.jsx(qe,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(C.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:()=>m(C.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:C.source.name,onValueChange:w=>{const M=a.find(B=>B.name===w);N(C.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:w,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(C.id).map(w=>e.jsx(t.SelectItem,{value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name]})},w.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:C.joinType,onValueChange:w=>N(C.id,{joinType:w}),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:C.target.name,onValueChange:w=>{const M=a.find(B=>B.name===w);N(C.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:w,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!C.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:C.source.name?p(C.source.name).map(w=>e.jsx(t.SelectItem,{value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,w.name===C.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},w.name)):[]})]})]})]}),C.source.name&&C.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(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),C.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:C.joinKeyGroups.map((w,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:w.operator,onValueChange:B=>T(C.id,M,B),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(C.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[w.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:w.keys.map((B,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:w.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:B.source.name,onValueChange:P=>b(C.id,M,R,"sourceColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:D(C.source.name).map(P=>e.jsx(t.SelectItem,{value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:B.operator,onValueChange:P=>b(C.id,M,R,"operator",P),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:B.target.name,onValueChange:P=>b(C.id,M,R,"targetColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:D(C.target.name).map(P=>e.jsx(t.SelectItem,{value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(C.id,M,R),children:e.jsx(t.X,{className:"size-3.5"})})]},B.id||R))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>j(C.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},w.id))})]})]})]},C.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 Ht({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.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(gr,{joinPlan:r,availableDataSources:o,onSave:l,onCancel:u,onRemove:i})]}),s]})}function jr({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 yr(){var m,N;Me(),t.useEditorStore(f=>f.card.dataSource);const s=t.useEditorStore(f=>f.frame),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.actions.updateCardConfig),r=((m=a==null?void 0:a.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[o,i]=L.useState(!1),l=((N=a==null?void 0:a.dataSource)==null?void 0:N.selectedEntities)||[],u=f=>{s.activeCardId&&(n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:f}),i(!1))},c=()=>{n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:void 0})},h=()=>{i(!1)},d=()=>{const f=[...r.joins].sort((v,p)=>v.sequence-p.sequence),g=r.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let x=`SELECT *
403
403
  FROM ${g.name}`;return f.forEach(v=>{const p=l.find(E=>E.name===v.target.name);if(!p)return;const k=v.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const j=E.keys.filter(b=>{var y,S,I,D;return((y=b.source)==null?void 0:y.name)&&((S=b.target)==null?void 0:S.name)&&((I=b.source)==null?void 0:I.entityName)&&((D=b.target)==null?void 0:D.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return j.length>1?`(${j.join(` ${E.operator} `)})`:j[0]}).filter(Boolean),T=k.length>1?k.join(" OR "):k[0]||"condition_here";x+=`
404
404
  ${v.joinType} JOIN ${p.name}
405
- ON ${T}`}),x};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(jr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx(Ht,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Ht,{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 br(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(c=>c.card.dataSource),{updateDataSource:i}=t.useEditorActions(),l={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...l,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"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"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",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-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((c,h)=>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:[c.name,e.jsx("button",{onClick:d=>{d.stopPropagation();const m=u.selectedEntities.filter(N=>!(N.name===c.name&&N.type===c.type));i({...l,...o,selectedEntities:m})},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"})})]},`${c.type}-${c.name}-${h}`)),u.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})]}),e.jsx(yr,{})]})]}),e.jsx(pr,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:u,fallbackDataSource:l})]})}const vr=[{id:"table",icon:He,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"stackedBar",icon:ut,label:"Stacked Bar Chart"},{id:"stackedLine",icon:Dt,label:"Stacked Line Chart"},{id:"scatter",icon:pt,label:"Scatter Chart"},{id:"bubble",icon:Et,label:"Bubble Chart"},{id:"pie",icon:xt,label:"Pie Chart"},{id:"doughnut",icon:ft,label:"Doughnut Chart"},{id:"funnel",icon:It,label:"Funnel Chart"},{id:"radar",icon:bt,label:"Radar Chart"},{id:"polarArea",icon:kt,label:"Polar Area Chart"},{id:"tornado",icon:Nt,label:"Tornado Chart"},{id:"range",icon:ht,label:"Range Chart"},{id:"kpi",icon:Tt,label:"KPI"},{id:"text",icon:Ut,label:"Text"},{id:"map",icon:yt,label:"Map"},{id:"custom",icon:vt,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:vr.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 ks=({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 Cr({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-muted-foreground",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-muted-foreground"})})]})]})]})}function Sr({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 wr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},h=m=>{const N={...s};delete N[m],a(N)},d=m=>{const N={...s};delete N[m],N[o]=l,a(N),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([m,N],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?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(m):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(m):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(m),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-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),u(N)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:N,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),u(N)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(m),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},m+f)),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 kr({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,hasPivotColumns:m=!1}){const{attributes:N,listeners:f,setNodeRef:g,transform:x,transition:v,isDragging:p}=t.useSortable({id:s.id}),[k,T]=L.useState(!1),[E,j]=L.useState(s.dateFormat||"YYYY-MM-DD"),[b,y]=L.useState(s.customFormat||""),[S,I]=L.useState(!!s.customFormat),[D,C]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,w]=L.useState(s.valueAliases||{}),M=q=>{q==="custom"?I(!0):(I(!1),j(q),a==="groupBy"&&h&&h(q,""))},B=q=>{y(q),a==="groupBy"&&h&&h("custom",q)},R=q=>{C(q),a==="groupBy"&&d&&d(q)},P=q=>{O(q),l&&l(q)},z=q=>{w(q),u&&u(q)},K={transform:t.CSS.Transform.toString(x),transition:v},J=t.getDataType(s.dataType),G=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,...N,...f,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 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(ks,{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:q=>{q.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:q=>{q.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:q=>{q.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(Cr,{label:s.label??"",onLabelChange:r}),G&&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"})]})]})}),G&&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-muted-foreground",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-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:S?"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(q=>e.jsx(t.SelectItem,{value:q.value,children:q.label},q.value))})]}),S&&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:b,onChange:q=>{q.stopPropagation(),B(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),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-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:q=>{c&&c(q)},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"})]})]})]})]}),m&&e.jsxs(e.Fragment,{children:[e.jsx(Sr,{aliasTemplate:F,onAliasTemplateChange:P}),e.jsx(wr,{valueAliases:A,onValueAliasesChange:z})]})]})]})]})}function Er({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-50 text-xs font-medium dark:bg-amber-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}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:m,hasPivotColumns:N=!1}){const{isOver:f,setNodeRef:g}=t.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),v=t.useEditorStore(T=>T.card),p=a.length>0,k=(T,E)=>{var b;!((b=v.config)!=null&&b.sortByColumns)||v.config.sortByColumns.findIndex(y=>y.id===T)===-1||x(v.id,T,{direction:E})};return s==="sortBy"&&m===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:"block text-sm font-medium",children:n}),e.jsx(Er,{concept:s})]}),e.jsx("div",{ref:g,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${f?"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 b=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(kr,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:y=>i(E,y),sortDirection:b,onSortDirectionChange:y=>k(T.id,y),onAggregationChange:l?y=>l(E,y):void 0,onAliasTemplateChange:h?y=>h(E,y):void 0,onValueAliasesChange:d?y=>d(E,y):void 0,onDateFormatChange:u?(y,S)=>u(E,y,S):void 0,onGranularityChange:c?y=>c(E,y):void 0,hasPivotColumns:N})})},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:"Rows",placeholder:"Drop fields to group data",onRemove:m=>o("groupBy",m),onLabelChange:(m,N)=>i("groupBy",m,N),onDateFormatChange:(m,N,f)=>u&&u(m,N,f),onGranularityChange:(m,N)=>c&&c(m,N)}),e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",onRemove:m=>o("pivotBy",m),onLabelChange:(m,N)=>i("pivotBy",m,N)}),e.jsx(Fe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:m=>o("metrics",m),onLabelChange:(m,N)=>i("metrics",m,N),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:m=>o("sortBy",m),onLabelChange:(m,N)=>i("sortBy",m,N),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:m,onValueAliasesChange:N}){t.useEditorStore(g=>g.showAIDialog);const{setShowAIDialog:f}=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(mt,{className:"text-brand h-5 w-5"}),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:m,onValueAliasesChange:N}),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(j=>j.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=j=>{const b=y=>{if(y.id===j){const S=u[0]||c;return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}]}}return{...y,groups:y.groups.map(b)}};r(b(n))},d=j=>{const b=y=>{if(y.id===j){const S=u[0]||c;return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}],groups:[]}]}}return{...y,groups:y.groups.map(b)}};r(b(n))},m=(j,b)=>{const y=S=>S.id===j?{...S,conditions:S.conditions.filter(I=>I.id!==b)}:{...S,groups:S.groups.map(y)};r(y(n))},N=(j,b)=>{const y=S=>S.id===j?{...S,groups:S.groups.filter(I=>I.id!==b)}:{...S,groups:S.groups.map(y)};r(y(n))},f=(j,b,y,S)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===j?{...D,conditions:D.conditions.map(C=>C.id===b?{...C,[y]:S}:C)}:{...D,groups:D.groups.map(I)};r(I(n))},g=(j,b,y)=>{const S=I=>I.id===j?{...I,conditions:I.conditions.map(D=>D.id===b?{...D,...y}:D)}:{...I,groups:I.groups.map(S)};r(S(n))},x=(j,b)=>{const y=S=>S.id===j?{...S,logicalOperator:b}:{...S,groups:S.groups.map(y)};r(y(n))},v=(j,b)=>{const y=S=>S.id===j?{...S,negate:b}:{...S,groups:S.groups.map(y)};r(y(n))},p=(j,b,y)=>{const S=I=>I.id===j?{...I,conditions:t.arrayMove(I.conditions,b,y)}:{...I,groups:I.groups.map(S)};r(S(n))},k=(j,b,y)=>{const S=I=>I.id===j?{...I,groups:t.arrayMove(I.groups,b,y)}:{...I,groups:I.groups.map(S)};r(S(n))},T=j=>{if(!j||j.conditions.length===0&&j.groups.length===0)return"-- No filters defined";const b=S=>{let I="";typeof S.field=="object"?I=S.field.entityName?`${S.field.entityName}.${S.field.name}`:S.field.name:I=String(S.field);const D=S.operator;let C=S.value;if(S.field.dataType==="string"&&!["in","not in"].includes(S.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(S.field.dataType==="date")(typeof C=="string"||C instanceof Date)&&(C=`DATE('${C}')`);else if(["in","not in"].includes(S.operator)){let F=[];Array.isArray(C)?F=C.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof C=="string"?F=C.split(",").map(O=>{const A=O.trim();return S.field.dataType==="string"?`'${A}'`:A}):typeof C=="number"&&(F=[String(C)]),C=`(${F.join(", ")})`}switch(D){case"contains":return typeof C=="string"?`${I} LIKE '%${C.replace(/'/g,"")}'`:`${I} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${I} LIKE '${C.replace(/'/g,"")}%'`:`${I} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${I} LIKE '%${C.replace(/'/g,"")}'`:`${I} LIKE '%${String(C)}'`;default:return`${I} ${D} ${C}`}},y=S=>{const I=S.conditions.map(b),D=S.groups.map(A=>y(A)),C=[...I,...D].filter(Boolean);if(C.length===0)return"";const F=C.join(` ${S.logicalOperator} `),O=C.length>1?`(${F})`:F;return S.negate?`NOT ${O}`:O};return y(j)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:h,addGroup:d,removeCondition:m,removeGroup:N,updateCondition:f,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:p,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(mt,{className:"h-3 w-3"});case"file":return e.jsx(hn,{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(tn,{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,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Mr(m[0].entityType),e.jsx("span",{children:m[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Ar(m[0].entityType)})]}),m.map(N=>e.jsxs(t.CommandItem,{value:N.id,onSelect:()=>{a(N),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)===N.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:N.label}),N.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:N.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:N.dataType}),N.description&&e.jsxs("span",{children:["• ",N.description]}),N.customFormat&&e.jsxs("span",{children:["• ",N.customFormat]})]})]})]},N.id))]},`${c}-${d}`))},c))})]})})]})}function Lt(s){var f;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=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:d,error:m}=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:m}}function Fr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=re.useState(!1),{filterValues:u}=Lt(s),c=d=>{n(a.filter(m=>m!==d))},h=d=>{a.includes(d)?n(a.filter(m=>m!==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 m=u.find(N=>N.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:N=>{N.key==="Enter"&&c(d)},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},onClick:N=>{N.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 Es=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=Es(n)}),a};function Br({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=Lt(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 zr=["=","!=",">",">=","<","<=","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 zr}}function Is({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:h,listeners:d,setNodeRef:m,transform:N,transition:f,isDragging:g}=t.useSortable({id:s.id}),{isPending:x,error:v}=Lt(s.field),p={transform:t.CSS.Transform.toString(N),transition:f};return e.jsxs("div",{ref:m,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/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"?x?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(Br,{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 $r({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:h,onReorderGroups:d,onAddCondition:m,onAddGroup:N,availableFields:f,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:p,setNodeRef:k,transform:T,transition:E,isDragging:j}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(T),transition:E},y=I=>{const{active:D,over:C}=I;if(C&&D.id!==C.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===C.id);F!==-1&&O!==-1&&h(s.id,F,O)}},S=I=>{const{active:D,over:C}=I;if(C&&D.id!==C.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===C.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:k,style:b,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${j?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),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:y,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(Is,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,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:()=>m(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:()=>N(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Gr({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:h,removeCondition:d,removeGroup:m,updateCondition:N,updateConditionFields:f,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:p,generateSQLPreview:k,hasAnyFilters:T,setCurrentFilters:E}=Tr({initialFilters:s,availableFields:a}),j=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[b,y]=L.useState(!1),S=(C,F,O)=>{const A=w=>w.id===C?{...w,conditions:w.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...w,groups:w.groups.map(A)};E(A(i))},I=(C,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:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:w,over:M}=A;if(M&&w.id!==M.id){const B=C.conditions.findIndex(P=>P.id===w.id),R=C.conditions.findIndex(P=>P.id===M.id);B!==-1&&R!==-1&&v(C.id,B,R)}},children:e.jsx(t.SortableContext,{items:C.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:C.conditions.map((A,w)=>e.jsx(Is,{condition:A,index:w,groupId:C.id,groupLogicalOperator:C.logicalOperator,onUpdateCondition:N,onUpdateField:S,onRemoveCondition:d,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:f},A.id))})}),e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:w,over:M}=A;if(M&&w.id!==M.id){const B=C.groups.findIndex(P=>P.id===w.id),R=C.groups.findIndex(P=>P.id===M.id);B!==-1&&R!==-1&&p(C.id,B,R)}},children:e.jsx(t.SortableContext,{items:C.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:C.groups.map(A=>I(A,F+1,C.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(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),b&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},C.id):e.jsx($r,{group:C,depth:F,parentGroupId:O,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:m,onUpdateCondition:N,onUpdateField:S,onRemoveCondition:d,onReorderConditions:v,onReorderGroups:p,onAddCondition:c,onAddGroup:h,availableFields:l,renderFilterGroup:I,updateConditionFields:f},C.id),D=Es(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-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:b,onCheckedChange:C=>y(!!C)}),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-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children: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(Gr,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Ds(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Ts(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Jr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v;const[o,i]=L.useState(null),l=t.useEditorStore(p=>p.card),u=(v=l==null?void 0:l.config)==null?void 0:v.joinPlan,c=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=L.useCallback(p=>p.startsWith("card-")?null:p.startsWith("source-")||a.find(k=>k.id===p)?"source":n("groupBy").find(k=>k.id===p)?"groupBy":n("metrics").find(k=>k.id===p)?"metrics":n("pivotBy").find(k=>k.id===p)?"pivotBy":n("sortBy").find(k=>k.id===p)?"sortBy":null,[a,n]),d=L.useCallback((p,k)=>{var T;return!u||!((T=u.baseEntity)!=null&&T.name)||!u.joins?!1:p===k||p===u.baseEntity.name||k===u.baseEntity.name?!0:u.joins.some(E=>{const j=dt(E.source),b=dt(E.target);return console.log(j,b),console.log(j===p&&b===k||j===k&&b===p),j===p&&b===k||j===k&&b===p})},[u]),m=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),N=(p,k)=>{const T=Ts(k,p),E=t.getDataType(p.dataType),j=E==="date",b={id:T,name:p.name,dataType:p.dataType,label:t.toLabel(p.name),qualifiedEntityName:p.qualifiedEntityName,entityId:p.entityId,entityName:p.entityName,entityType:p.entityType};if(k==="metrics"){const y=E==="number"?"SUM":"COUNT",S=Ds(p.label,y);return{...b,role:"metric",label:S,aggregate:y}}return k==="groupBy"?{...b,role:"groupby",...j&&{granularity:"month"}}:k==="pivotBy"?{...b,role:"pivotby"}:k==="sortBy"?{...b,role:"sortby",direction:"asc"}:null},f=L.useCallback(p=>{i(p.active.id)},[]),g=L.useCallback(p=>{const{active:k,over:T}=p;if(!T||!s){i(null);return}const E=k.id,j=T.id,b=h(E),y=h(j)||j;if(b==="source"&&y!=="source"){const S=[...a].find(O=>O.id===E);if(!S){i(null);return}const I=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(I.length>0){const O=I[0].qualifiedEntityName;if(!O){i(null);return}if(O!==S.qualifiedEntityName&&S.qualifiedEntityName)if(u){if(!d(O,S.qualifiedEntityName)){m(),i(null);return}}else{m(),i(null);return}}const D=n(y);if(D.some(O=>O.name===S.name&&O.qualifiedEntityName===S.qualifiedEntityName)){i(null);return}const F=N(S,y);i(null),r(y,[...D,F]);return}if(b&&y&&b!=="source"&&y!=="source"&&b!==y){const S=n(b),I=n(y),D=S.find(O=>O.id===E);if(!D){i(null);return}const C=N(D,y);i(null);const F=S.filter(O=>O.id!==E);r(b,F),r(y,[...I,C]);return}if(b&&y&&b===y&&b!=="source"){const S=n(b),I=S.findIndex(C=>C.id===E),D=S.findIndex(C=>C.id===j);if(I!==D){const C=t.arrayMove(S,I,D);r(b,C)}}i(null)},[s,a,n,r,h,u,m,d]),x=o?c.find(p=>p.id===o):null;return{activeId:o,activeField:x,handleDragStart:f,handleDragEnd:g}}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,m=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,dateFormat:j.dateFormat,customFormat:j.customFormat,granularity:j.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,direction:j.direction}));case"source":return[];default:return[]}},[s]),N=L.useCallback((E,j)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:j});break}case"metrics":{a(d,{metricColumns:j});break}case"pivotBy":{a(d,{pivotByColumns:j});break}case"sortBy":{a(d,{sortByColumns:j});break}}},[d,a]),f=L.useCallback((E,j,b)=>{if(!d)return;const S=m(E)[j];if(S)switch(E){case"groupBy":n(d,S.id,{label:b});break;case"metrics":r(d,S.id,{label:b});break;case"pivotBy":o(d,S.id,{label:b});break;case"sortBy":i(d,S.id,{label:b});break}},[d,m,n,r,o,i]),g=L.useCallback((E,j)=>{if(!d)return;const y=m("metrics")[E];y&&r(d,y.id,{aggregate:j,label:Ds(y.name,j)})},[d,m,r]),x=L.useCallback((E,j,b)=>{if(!d)return;const S=m("groupBy")[E];if(!S)return;const I={dateFormat:j};j==="custom"&&b?I.customFormat=b:I.customFormat=void 0,n(d,S.id,I)},[d,m,n]),v=L.useCallback((E,j)=>{if(!d)return;const y=m("groupBy")[E];y&&n(d,y.id,{granularity:j})},[d,m,n]),p=L.useCallback((E,j)=>{if(!d)return;const y=m("metrics")[E];y&&r(d,y.id,{aliasTemplate:j})},[d,m,r]),k=L.useCallback((E,j)=>{if(console.log("handleValueAliasesChange",E,j),!d)return;console.log("handleValueAliasesChange",E,j);const y=m("metrics")[E];y&&(console.log("handleValueAliasesChange",j),r(d,y.id,{valueAliases:j}))},[d,m,r]),T=L.useCallback((E,j)=>{if(!d)return;const y=m(E)[j];if(y)switch(E){case"groupBy":l(d,y.id);break;case"metrics":u(d,y.id);break;case"pivotBy":c(d,y.id);break;case"sortBy":h(d,y.id);break}},[d,m,l,u,c,h]);return{getFieldsForContainer:m,setFieldsForContainer:N,updateLabel:f,handleAggregationChange:g,handleDateFormatChange:x,handleGranularityChange:v,handleAliasTemplateChange:p,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 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Results"}),e.jsx(t.TabsTrigger,{value:"sql",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"SQL"})]})})}const Kr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Qr(){var c,h;const s=t.useEditorStore(d=>d.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),l=d=>{if(d==="custom"){r(!0);return}r(!1),a(s.id,parseInt(d))},u=d=>{const m=d.target.value;i(m),m&&!isNaN(parseInt(m))&&a(s.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:u,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((h=(c=s.config)==null?void 0:c.rowLimit)==null?void 0:h.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Kr.map(d=>e.jsx(t.SelectItem,{value:d.value,children:d.label},d.value))})]})})}function Wr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:h,columns:d,columnsLoading:m,columnsError:N}){var S;const f=t.useEditorStore(I=>I.card),{updateCardConfig:g}=t.useEditorActions(),x=t.useEditorStore(I=>I.showAIDialog),{data:v,errorMessage:p,isPending:k,isLoading:T,isFetching:E}=t.useDashboardCardQuery(h);function j(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":N?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const b=I=>{if(!f.config)return;if(!I.length){g(f.id,{...f.config,sortByColumns:[]});return}const D=f.config,C=I.map(({id:F,desc:O})=>{var B,R;const A=(B=D.metricColumns)==null?void 0:B.find(P=>P.label===F),w=(R=D.groupByColumns)==null?void 0:R.find(P=>P.label===F),M=A||w;return M?{id:Ts("sortBy",M),name:M.name,dataType:M.dataType,label:M.label,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,role:"sortby",direction:O?"desc":"asc"}:null}).filter(F=>F!==null);g(f.id,{...D,sortByColumns:C})},y=L.useMemo(()=>{var I,D;return(D=(I=f.config)==null?void 0:I.sortByColumns)==null?void 0:D.map(C=>({id:C.label,desc:C.direction==="desc"}))},[(S=f.config)==null?void 0:S.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&&j(),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.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Yr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"gap-1",onClick:u,children:[e.jsx(gt,{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(Qr,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end",{"justify-between":x}),children:[s==="chart"&&x&&e.jsx(fs,{}),e.jsx("div",{className:"opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(gs,{})})]})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:T||E?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(js,{})}),s==="table"&&(v==null?void 0:v.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:v==null?void 0:v.records,onSortChange:b,sortState:y})}),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",children:"Generated SQL Query"}),e.jsx(is,{sql:v==null?void 0:v.sql,error:p})]})})]})]})]})}function Xr({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-muted-foreground"}),e.jsx(ks,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const Zr=()=>{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 eo(){var _,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(()=>Zr(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},m=()=>{console.log("Advanced mode toggled")},N=()=>{i(!0)},f=Y=>{u(Y)},g=t.useEditorStore(Y=>Y.frame),x=t.useEditorStore(Y=>Y.card);t.useEditorStore(Y=>Y.activeTabCardId),t.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:v,removeCard:p,updateCard:k,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:j=[],isLoading:b,error:y}=Me(),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=x,{getFieldsForContainer:D,setFieldsForContainer:C,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:w,handleAliasTemplateChange:M,handleValueAliasesChange:B,removeField:R}=Ur(I),{activeField:P,handleDragStart:z,handleDragEnd:K}=Jr({activeCardId:g.activeCardId,sourceFields:j,getFieldsForContainer:D,setFieldsForContainer:C}),J=(Y,Z)=>{Z&&E(Y,Z)},G=Y=>{var Z;k(Y,{config:{...(Z=g.cards.find(de=>de.id===Y))==null?void 0:Z.config,filters:void 0}})},U=j,q=Y=>{if(!Y)return 0;let Z=Y.conditions.length;return Y.groups.forEach(de=>{Z+=q(de)}),Z},V=q(((_=I==null?void 0:I.config)==null?void 0:_.filters)||null);return e.jsxs(t.DndContext,{sensors:S,collisionDetection:t.closestCenter,onDragStart:z,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(br,{}),!l&&e.jsx(Dr,{selectedChart:c,onChartChange:f,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:R,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:w,onAliasTemplateChange:M,onValueAliasesChange:B}),e.jsx(Wr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:d,onAdvancedToggle:m,onFiltersClick:N,filterCount:V,activeCard:I,dataSourceState:x.dataSource||t.EMPTY_DATA_SOURCE,columns:j,columnsLoading:b,columnsError:y,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:G,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Xr,{activeField:P||null})})]})}function to({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:m,handleDragStart:N,handleDragCancel:f,sensors:g}=Un();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 x(k){k<1?u(!1):o||u(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(os,{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:x,defaultSize:0,children:e.jsx(Gt,{})})]})]})}function p(){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(eo,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Gt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:g,onDragStart:N,onDragEnd:m,onDragOver:d,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):p()})}function so(){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(to,{onSave:o,onClose:i})})}function no(){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}=Cs();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(St,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function ao(){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(os,{type:"filter",ColumnsComponent:()=>e.jsx(no,{})})})]})}function ro(){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 oo(){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(ro,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ao,{})})]})}function io(){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 lo({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(io,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(_n,{}),e.jsx(so,{}),e.jsx(oo,{})]})]})]})})}exports.DashboardPlus=lo;exports.ScheduleDashboard=as;exports.SelectComponent=ve;exports.cleanCard=ts;exports.downloadPdf=ns;exports.getDashbaordStateWithoutData=Ct;
405
+ ON ${T}`}),x};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(jr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx(Ht,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:h,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Ht,{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 br(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(c=>c.card.dataSource),{updateDataSource:i}=t.useEditorActions(),l={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...l,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"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"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",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-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((c,h)=>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:[t.getDisplayName(c),e.jsx("button",{onClick:d=>{d.stopPropagation();const m=u.selectedEntities.filter(N=>!(N.name===c.name&&N.type===c.type));i({...l,...o,selectedEntities:m})},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"})})]},`${c.type}-${c.name}-${h}`)),u.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})]}),e.jsx(yr,{})]})]}),e.jsx(pr,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:u,fallbackDataSource:l})]})}const vr=[{id:"table",icon:He,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"stackedBar",icon:ut,label:"Stacked Bar Chart"},{id:"stackedLine",icon:Dt,label:"Stacked Line Chart"},{id:"scatter",icon:pt,label:"Scatter Chart"},{id:"bubble",icon:Et,label:"Bubble Chart"},{id:"pie",icon:xt,label:"Pie Chart"},{id:"doughnut",icon:ft,label:"Doughnut Chart"},{id:"funnel",icon:It,label:"Funnel Chart"},{id:"radar",icon:bt,label:"Radar Chart"},{id:"polarArea",icon:kt,label:"Polar Area Chart"},{id:"tornado",icon:Nt,label:"Tornado Chart"},{id:"range",icon:ht,label:"Range Chart"},{id:"kpi",icon:Tt,label:"KPI"},{id:"text",icon:Ut,label:"Text"},{id:"map",icon:yt,label:"Map"},{id:"custom",icon:vt,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:vr.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 ks=({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 Cr({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-muted-foreground",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-muted-foreground"})})]})]})]})}function Sr({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 wr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},h=m=>{const N={...s};delete N[m],a(N)},d=m=>{const N={...s};delete N[m],N[o]=l,a(N),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([m,N],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?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(m):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(m):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(m),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-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),u(N)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:N,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),u(N)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(m),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},m+f)),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 kr({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:h,onGranularityChange:d,hasPivotColumns:m=!1}){const{attributes:N,listeners:f,setNodeRef:g,transform:x,transition:v,isDragging:p}=t.useSortable({id:s.id}),[k,T]=L.useState(!1),[E,j]=L.useState(s.dateFormat||"YYYY-MM-DD"),[b,y]=L.useState(s.customFormat||""),[S,I]=L.useState(!!s.customFormat),[D,C]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,w]=L.useState(s.valueAliases||{}),M=q=>{q==="custom"?I(!0):(I(!1),j(q),a==="groupBy"&&h&&h(q,""))},B=q=>{y(q),a==="groupBy"&&h&&h("custom",q)},R=q=>{C(q),a==="groupBy"&&d&&d(q)},P=q=>{O(q),l&&l(q)},z=q=>{w(q),u&&u(q)},K={transform:t.CSS.Transform.toString(x),transition:v},J=t.getDataType(s.dataType),G=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,...N,...f,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 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(ks,{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:q=>{q.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:q=>{q.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:q=>{q.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(Cr,{label:s.label??"",onLabelChange:r}),G&&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"})]})]})}),G&&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-muted-foreground",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-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:S?"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(q=>e.jsx(t.SelectItem,{value:q.value,children:q.label},q.value))})]}),S&&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:b,onChange:q=>{q.stopPropagation(),B(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),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-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:q=>{c&&c(q)},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"})]})]})]})]}),m&&e.jsxs(e.Fragment,{children:[e.jsx(Sr,{aliasTemplate:F,onAliasTemplateChange:P}),e.jsx(wr,{valueAliases:A,onValueAliasesChange:z})]})]})]})]})}function Er({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-50 text-xs font-medium dark:bg-amber-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}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:m,hasPivotColumns:N=!1}){const{isOver:f,setNodeRef:g}=t.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),v=t.useEditorStore(T=>T.card),p=a.length>0,k=(T,E)=>{var b;!((b=v.config)!=null&&b.sortByColumns)||v.config.sortByColumns.findIndex(y=>y.id===T)===-1||x(v.id,T,{direction:E})};return s==="sortBy"&&m===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:"block text-sm font-medium",children:n}),e.jsx(Er,{concept:s})]}),e.jsx("div",{ref:g,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${f?"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 b=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(kr,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:y=>i(E,y),sortDirection:b,onSortDirectionChange:y=>k(T.id,y),onAggregationChange:l?y=>l(E,y):void 0,onAliasTemplateChange:h?y=>h(E,y):void 0,onValueAliasesChange:d?y=>d(E,y):void 0,onDateFormatChange:u?(y,S)=>u(E,y,S):void 0,onGranularityChange:c?y=>c(E,y):void 0,hasPivotColumns:N})})},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:"Rows",placeholder:"Drop fields to group data",onRemove:m=>o("groupBy",m),onLabelChange:(m,N)=>i("groupBy",m,N),onDateFormatChange:(m,N,f)=>u&&u(m,N,f),onGranularityChange:(m,N)=>c&&c(m,N)}),e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",onRemove:m=>o("pivotBy",m),onLabelChange:(m,N)=>i("pivotBy",m,N)}),e.jsx(Fe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:m=>o("metrics",m),onLabelChange:(m,N)=>i("metrics",m,N),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:m=>o("sortBy",m),onLabelChange:(m,N)=>i("sortBy",m,N),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:m,onValueAliasesChange:N}){t.useEditorStore(g=>g.showAIDialog);const{setShowAIDialog:f}=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(mt,{className:"text-brand h-5 w-5"}),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:m,onValueAliasesChange:N}),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(j=>j.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=j=>{const b=y=>{if(y.id===j){const S=u[0]||c;return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}]}}return{...y,groups:y.groups.map(b)}};r(b(n))},d=j=>{const b=y=>{if(y.id===j){const S=u[0]||c;return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}],groups:[]}]}}return{...y,groups:y.groups.map(b)}};r(b(n))},m=(j,b)=>{const y=S=>S.id===j?{...S,conditions:S.conditions.filter(I=>I.id!==b)}:{...S,groups:S.groups.map(y)};r(y(n))},N=(j,b)=>{const y=S=>S.id===j?{...S,groups:S.groups.filter(I=>I.id!==b)}:{...S,groups:S.groups.map(y)};r(y(n))},f=(j,b,y,S)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===j?{...D,conditions:D.conditions.map(C=>C.id===b?{...C,[y]:S}:C)}:{...D,groups:D.groups.map(I)};r(I(n))},g=(j,b,y)=>{const S=I=>I.id===j?{...I,conditions:I.conditions.map(D=>D.id===b?{...D,...y}:D)}:{...I,groups:I.groups.map(S)};r(S(n))},x=(j,b)=>{const y=S=>S.id===j?{...S,logicalOperator:b}:{...S,groups:S.groups.map(y)};r(y(n))},v=(j,b)=>{const y=S=>S.id===j?{...S,negate:b}:{...S,groups:S.groups.map(y)};r(y(n))},p=(j,b,y)=>{const S=I=>I.id===j?{...I,conditions:t.arrayMove(I.conditions,b,y)}:{...I,groups:I.groups.map(S)};r(S(n))},k=(j,b,y)=>{const S=I=>I.id===j?{...I,groups:t.arrayMove(I.groups,b,y)}:{...I,groups:I.groups.map(S)};r(S(n))},T=j=>{if(!j||j.conditions.length===0&&j.groups.length===0)return"-- No filters defined";const b=S=>{let I="";typeof S.field=="object"?I=S.field.entityName?`${S.field.entityName}.${S.field.name}`:S.field.name:I=String(S.field);const D=S.operator;let C=S.value;if(S.field.dataType==="string"&&!["in","not in"].includes(S.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(S.field.dataType==="date")(typeof C=="string"||C instanceof Date)&&(C=`DATE('${C}')`);else if(["in","not in"].includes(S.operator)){let F=[];Array.isArray(C)?F=C.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof C=="string"?F=C.split(",").map(O=>{const A=O.trim();return S.field.dataType==="string"?`'${A}'`:A}):typeof C=="number"&&(F=[String(C)]),C=`(${F.join(", ")})`}switch(D){case"contains":return typeof C=="string"?`${I} LIKE '%${C.replace(/'/g,"")}'`:`${I} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${I} LIKE '${C.replace(/'/g,"")}%'`:`${I} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${I} LIKE '%${C.replace(/'/g,"")}'`:`${I} LIKE '%${String(C)}'`;default:return`${I} ${D} ${C}`}},y=S=>{const I=S.conditions.map(b),D=S.groups.map(A=>y(A)),C=[...I,...D].filter(Boolean);if(C.length===0)return"";const F=C.join(` ${S.logicalOperator} `),O=C.length>1?`(${F})`:F;return S.negate?`NOT ${O}`:O};return y(j)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:h,addGroup:d,removeCondition:m,removeGroup:N,updateCondition:f,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:p,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(mt,{className:"h-3 w-3"});case"file":return e.jsx(hn,{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(tn,{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,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Mr(m[0].entityType),e.jsx("span",{children:m[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Ar(m[0].entityType)})]}),m.map(N=>e.jsxs(t.CommandItem,{value:N.id,onSelect:()=>{a(N),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)===N.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:N.label}),N.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:N.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:N.dataType}),N.description&&e.jsxs("span",{children:["• ",N.description]}),N.customFormat&&e.jsxs("span",{children:["• ",N.customFormat]})]})]})]},N.id))]},`${c}-${d}`))},c))})]})})]})}function Lt(s){var f;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=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:d,error:m}=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:m}}function Fr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=re.useState(!1),{filterValues:u}=Lt(s),c=d=>{n(a.filter(m=>m!==d))},h=d=>{a.includes(d)?n(a.filter(m=>m!==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 m=u.find(N=>N.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:N=>{N.key==="Enter"&&c(d)},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},onClick:N=>{N.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 Es=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=Es(n)}),a};function Br({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=Lt(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 zr=["=","!=",">",">=","<","<=","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 zr}}function Is({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:h,listeners:d,setNodeRef:m,transform:N,transition:f,isDragging:g}=t.useSortable({id:s.id}),{isPending:x,error:v}=Lt(s.field),p={transform:t.CSS.Transform.toString(N),transition:f};return e.jsxs("div",{ref:m,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/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"?x?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(Br,{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 $r({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:h,onReorderGroups:d,onAddCondition:m,onAddGroup:N,availableFields:f,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:p,setNodeRef:k,transform:T,transition:E,isDragging:j}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(T),transition:E},y=I=>{const{active:D,over:C}=I;if(C&&D.id!==C.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===C.id);F!==-1&&O!==-1&&h(s.id,F,O)}},S=I=>{const{active:D,over:C}=I;if(C&&D.id!==C.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===C.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:k,style:b,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${j?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),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:y,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(Is,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,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:()=>m(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:()=>N(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Gr({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:h,removeCondition:d,removeGroup:m,updateCondition:N,updateConditionFields:f,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:p,generateSQLPreview:k,hasAnyFilters:T,setCurrentFilters:E}=Tr({initialFilters:s,availableFields:a}),j=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[b,y]=L.useState(!1),S=(C,F,O)=>{const A=w=>w.id===C?{...w,conditions:w.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...w,groups:w.groups.map(A)};E(A(i))},I=(C,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:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:w,over:M}=A;if(M&&w.id!==M.id){const B=C.conditions.findIndex(P=>P.id===w.id),R=C.conditions.findIndex(P=>P.id===M.id);B!==-1&&R!==-1&&v(C.id,B,R)}},children:e.jsx(t.SortableContext,{items:C.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:C.conditions.map((A,w)=>e.jsx(Is,{condition:A,index:w,groupId:C.id,groupLogicalOperator:C.logicalOperator,onUpdateCondition:N,onUpdateField:S,onRemoveCondition:d,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:f},A.id))})}),e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:w,over:M}=A;if(M&&w.id!==M.id){const B=C.groups.findIndex(P=>P.id===w.id),R=C.groups.findIndex(P=>P.id===M.id);B!==-1&&R!==-1&&p(C.id,B,R)}},children:e.jsx(t.SortableContext,{items:C.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:C.groups.map(A=>I(A,F+1,C.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(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),b&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(C.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},C.id):e.jsx($r,{group:C,depth:F,parentGroupId:O,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:m,onUpdateCondition:N,onUpdateField:S,onRemoveCondition:d,onReorderConditions:v,onReorderGroups:p,onAddCondition:c,onAddGroup:h,availableFields:l,renderFilterGroup:I,updateConditionFields:f},C.id),D=Es(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-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:b,onCheckedChange:C=>y(!!C)}),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-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children: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(Gr,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Ds(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Ts(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Jr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v;const[o,i]=L.useState(null),l=t.useEditorStore(p=>p.card),u=(v=l==null?void 0:l.config)==null?void 0:v.joinPlan,c=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=L.useCallback(p=>p.startsWith("card-")?null:p.startsWith("source-")||a.find(k=>k.id===p)?"source":n("groupBy").find(k=>k.id===p)?"groupBy":n("metrics").find(k=>k.id===p)?"metrics":n("pivotBy").find(k=>k.id===p)?"pivotBy":n("sortBy").find(k=>k.id===p)?"sortBy":null,[a,n]),d=L.useCallback((p,k)=>{var T;return!u||!((T=u.baseEntity)!=null&&T.name)||!u.joins?!1:p===k||p===u.baseEntity.name||k===u.baseEntity.name?!0:u.joins.some(E=>{const j=dt(E.source),b=dt(E.target);return console.log(j,b),console.log(j===p&&b===k||j===k&&b===p),j===p&&b===k||j===k&&b===p})},[u]),m=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),N=(p,k)=>{const T=Ts(k,p),E=t.getDataType(p.dataType),j=E==="date",b={id:T,name:p.name,dataType:p.dataType,label:t.toLabel(p.name),qualifiedEntityName:p.qualifiedEntityName,entityId:p.entityId,entityName:p.entityName,entityType:p.entityType};if(k==="metrics"){const y=E==="number"?"SUM":"COUNT",S=Ds(p.label,y);return{...b,role:"metric",label:S,aggregate:y}}return k==="groupBy"?{...b,role:"groupby",...j&&{granularity:"month"}}:k==="pivotBy"?{...b,role:"pivotby"}:k==="sortBy"?{...b,role:"sortby",direction:"asc"}:null},f=L.useCallback(p=>{i(p.active.id)},[]),g=L.useCallback(p=>{const{active:k,over:T}=p;if(!T||!s){i(null);return}const E=k.id,j=T.id,b=h(E),y=h(j)||j;if(b==="source"&&y!=="source"){const S=[...a].find(O=>O.id===E);if(!S){i(null);return}const I=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(I.length>0){const O=I[0].qualifiedEntityName;if(!O){i(null);return}if(O!==S.qualifiedEntityName&&S.qualifiedEntityName)if(u){if(!d(O,S.qualifiedEntityName)){m(),i(null);return}}else{m(),i(null);return}}const D=n(y);if(D.some(O=>O.name===S.name&&O.qualifiedEntityName===S.qualifiedEntityName)){i(null);return}const F=N(S,y);i(null),r(y,[...D,F]);return}if(b&&y&&b!=="source"&&y!=="source"&&b!==y){const S=n(b),I=n(y),D=S.find(O=>O.id===E);if(!D){i(null);return}const C=N(D,y);i(null);const F=S.filter(O=>O.id!==E);r(b,F),r(y,[...I,C]);return}if(b&&y&&b===y&&b!=="source"){const S=n(b),I=S.findIndex(C=>C.id===E),D=S.findIndex(C=>C.id===j);if(I!==D){const C=t.arrayMove(S,I,D);r(b,C)}}i(null)},[s,a,n,r,h,u,m,d]),x=o?c.find(p=>p.id===o):null;return{activeId:o,activeField:x,handleDragStart:f,handleDragEnd:g}}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,m=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,dateFormat:j.dateFormat,customFormat:j.customFormat,granularity:j.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,direction:j.direction}));case"source":return[];default:return[]}},[s]),N=L.useCallback((E,j)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:j});break}case"metrics":{a(d,{metricColumns:j});break}case"pivotBy":{a(d,{pivotByColumns:j});break}case"sortBy":{a(d,{sortByColumns:j});break}}},[d,a]),f=L.useCallback((E,j,b)=>{if(!d)return;const S=m(E)[j];if(S)switch(E){case"groupBy":n(d,S.id,{label:b});break;case"metrics":r(d,S.id,{label:b});break;case"pivotBy":o(d,S.id,{label:b});break;case"sortBy":i(d,S.id,{label:b});break}},[d,m,n,r,o,i]),g=L.useCallback((E,j)=>{if(!d)return;const y=m("metrics")[E];y&&r(d,y.id,{aggregate:j,label:Ds(y.name,j)})},[d,m,r]),x=L.useCallback((E,j,b)=>{if(!d)return;const S=m("groupBy")[E];if(!S)return;const I={dateFormat:j};j==="custom"&&b?I.customFormat=b:I.customFormat=void 0,n(d,S.id,I)},[d,m,n]),v=L.useCallback((E,j)=>{if(!d)return;const y=m("groupBy")[E];y&&n(d,y.id,{granularity:j})},[d,m,n]),p=L.useCallback((E,j)=>{if(!d)return;const y=m("metrics")[E];y&&r(d,y.id,{aliasTemplate:j})},[d,m,r]),k=L.useCallback((E,j)=>{if(console.log("handleValueAliasesChange",E,j),!d)return;console.log("handleValueAliasesChange",E,j);const y=m("metrics")[E];y&&(console.log("handleValueAliasesChange",j),r(d,y.id,{valueAliases:j}))},[d,m,r]),T=L.useCallback((E,j)=>{if(!d)return;const y=m(E)[j];if(y)switch(E){case"groupBy":l(d,y.id);break;case"metrics":u(d,y.id);break;case"pivotBy":c(d,y.id);break;case"sortBy":h(d,y.id);break}},[d,m,l,u,c,h]);return{getFieldsForContainer:m,setFieldsForContainer:N,updateLabel:f,handleAggregationChange:g,handleDateFormatChange:x,handleGranularityChange:v,handleAliasTemplateChange:p,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 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Results"}),e.jsx(t.TabsTrigger,{value:"sql",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"SQL"})]})})}const Kr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Qr(){var c,h;const s=t.useEditorStore(d=>d.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),l=d=>{if(d==="custom"){r(!0);return}r(!1),a(s.id,parseInt(d))},u=d=>{const m=d.target.value;i(m),m&&!isNaN(parseInt(m))&&a(s.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:u,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((h=(c=s.config)==null?void 0:c.rowLimit)==null?void 0:h.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Kr.map(d=>e.jsx(t.SelectItem,{value:d.value,children:d.label},d.value))})]})})}function Wr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:h,columns:d,columnsLoading:m,columnsError:N}){var S;const f=t.useEditorStore(I=>I.card),{updateCardConfig:g}=t.useEditorActions(),x=t.useEditorStore(I=>I.showAIDialog),{data:v,errorMessage:p,isPending:k,isLoading:T,isFetching:E}=t.useDashboardCardQuery(h);function j(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":N?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const b=I=>{if(!f.config)return;if(!I.length){g(f.id,{...f.config,sortByColumns:[]});return}const D=f.config,C=I.map(({id:F,desc:O})=>{var B,R;const A=(B=D.metricColumns)==null?void 0:B.find(P=>P.label===F),w=(R=D.groupByColumns)==null?void 0:R.find(P=>P.label===F),M=A||w;return M?{id:Ts("sortBy",M),name:M.name,dataType:M.dataType,label:M.label,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,role:"sortby",direction:O?"desc":"asc"}:null}).filter(F=>F!==null);g(f.id,{...D,sortByColumns:C})},y=L.useMemo(()=>{var I,D;return(D=(I=f.config)==null?void 0:I.sortByColumns)==null?void 0:D.map(C=>({id:C.label,desc:C.direction==="desc"}))},[(S=f.config)==null?void 0:S.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&&j(),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.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Yr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"gap-1",onClick:u,children:[e.jsx(gt,{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(Qr,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end",{"justify-between":x}),children:[s==="chart"&&x&&e.jsx(fs,{}),e.jsx("div",{className:"opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(gs,{})})]})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:T||E?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(js,{})}),s==="table"&&(v==null?void 0:v.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:v==null?void 0:v.records,onSortChange:b,sortState:y})}),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",children:"Generated SQL Query"}),e.jsx(is,{sql:v==null?void 0:v.sql,error:p})]})})]})]})]})}function Xr({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-muted-foreground"}),e.jsx(ks,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const Zr=()=>{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 eo(){var _,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(()=>Zr(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},m=()=>{console.log("Advanced mode toggled")},N=()=>{i(!0)},f=Y=>{u(Y)},g=t.useEditorStore(Y=>Y.frame),x=t.useEditorStore(Y=>Y.card);t.useEditorStore(Y=>Y.activeTabCardId),t.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:v,removeCard:p,updateCard:k,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:j=[],isLoading:b,error:y}=Me(),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=x,{getFieldsForContainer:D,setFieldsForContainer:C,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:w,handleAliasTemplateChange:M,handleValueAliasesChange:B,removeField:R}=Ur(I),{activeField:P,handleDragStart:z,handleDragEnd:K}=Jr({activeCardId:g.activeCardId,sourceFields:j,getFieldsForContainer:D,setFieldsForContainer:C}),J=(Y,Z)=>{Z&&E(Y,Z)},G=Y=>{var Z;k(Y,{config:{...(Z=g.cards.find(de=>de.id===Y))==null?void 0:Z.config,filters:void 0}})},U=j,q=Y=>{if(!Y)return 0;let Z=Y.conditions.length;return Y.groups.forEach(de=>{Z+=q(de)}),Z},V=q(((_=I==null?void 0:I.config)==null?void 0:_.filters)||null);return e.jsxs(t.DndContext,{sensors:S,collisionDetection:t.closestCenter,onDragStart:z,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(br,{}),!l&&e.jsx(Dr,{selectedChart:c,onChartChange:f,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:R,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:w,onAliasTemplateChange:M,onValueAliasesChange:B}),e.jsx(Wr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:d,onAdvancedToggle:m,onFiltersClick:N,filterCount:V,activeCard:I,dataSourceState:x.dataSource||t.EMPTY_DATA_SOURCE,columns:j,columnsLoading:b,columnsError:y,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:G,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Xr,{activeField:P||null})})]})}function to({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:m,handleDragStart:N,handleDragCancel:f,sensors:g}=Un();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 x(k){k<1?u(!1):o||u(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(os,{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:x,defaultSize:0,children:e.jsx(Gt,{})})]})]})}function p(){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(eo,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Gt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:g,onDragStart:N,onDragEnd:m,onDragOver:d,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):p()})}function so(){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(to,{onSave:o,onClose:i})})}function no(){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}=Cs();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(St,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function ao(){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(os,{type:"filter",ColumnsComponent:()=>e.jsx(no,{})})})]})}function ro(){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 oo(){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(ro,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ao,{})})]})}function io(){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 lo({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(io,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(_n,{}),e.jsx(so,{}),e.jsx(oo,{})]})]})]})})}exports.DashboardPlus=lo;exports.ScheduleDashboard=as;exports.SelectComponent=ve;exports.cleanCard=ts;exports.downloadPdf=ns;exports.getDashbaordStateWithoutData=Ct;