react-semaphor 0.0.607 → 0.0.608

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 Zs=t=>{throw TypeError(t)};var vs=(t,a,n)=>a.has(t)||Zs("Cannot "+n);var oe=(t,a,n)=>(vs(t,a,"read from private field"),n?n.call(t):a.get(t)),qe=(t,a,n)=>a.has(t)?Zs("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Ye=(t,a,n,r)=>(vs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Ge=(t,a,n)=>(vs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-CLgNERAd.js"),A=require("react");require("react-dom");function ba(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const pe=ba(A);var Me,Le,xe,we,ke,ms,Is,ft,Na=(ft=class extends s.Subscribable{constructor(a,n){super();qe(this,ke);qe(this,Me);qe(this,Le);qe(this,xe);qe(this,we);Ye(this,Me,a),this.setOptions(n),this.bindMethods(),Ge(this,ke,ms).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=oe(this,Me).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||oe(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:oe(this,xe),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=oe(this,xe))==null?void 0:r.state.status)==="pending"&&oe(this,xe).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=oe(this,xe))==null||a.removeObserver(this)}onMutationUpdate(a){Ge(this,ke,ms).call(this),Ge(this,ke,Is).call(this,a)}getCurrentResult(){return oe(this,Le)}reset(){var a;(a=oe(this,xe))==null||a.removeObserver(this),Ye(this,xe,void 0),Ge(this,ke,ms).call(this),Ge(this,ke,Is).call(this)}mutate(a,n){var r;return Ye(this,we,n),(r=oe(this,xe))==null||r.removeObserver(this),Ye(this,xe,oe(this,Me).getMutationCache().build(oe(this,Me),this.options)),oe(this,xe).addObserver(this),oe(this,xe).execute(a)}},Me=new WeakMap,Le=new WeakMap,xe=new WeakMap,we=new WeakMap,ke=new WeakSet,ms=function(){var n;const a=((n=oe(this,xe))==null?void 0:n.state)??s.getDefaultState();Ye(this,Le,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Is=function(a){s.notifyManager.batch(()=>{var n,r,l,o,c,i,d,u;if(oe(this,we)&&this.hasListeners()){const m=oe(this,Le).variables,h=oe(this,Le).context;(a==null?void 0:a.type)==="success"?((r=(n=oe(this,we)).onSuccess)==null||r.call(n,a.data,m,h),(o=(l=oe(this,we)).onSettled)==null||o.call(l,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=oe(this,we)).onError)==null||i.call(c,a.error,m,h),(u=(d=oe(this,we)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(oe(this,Le))})})},ft);function Be(t,a){const n=s.useQueryClient(),[r]=pe.useState(()=>new Na(n,t));pe.useEffect(()=>{r.setOptions(t)},[r,t]);const l=pe.useSyncExternalStore(pe.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=pe.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
1
+ "use strict";var Zs=t=>{throw TypeError(t)};var vs=(t,a,n)=>a.has(t)||Zs("Cannot "+n);var oe=(t,a,n)=>(vs(t,a,"read from private field"),n?n.call(t):a.get(t)),qe=(t,a,n)=>a.has(t)?Zs("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Ye=(t,a,n,r)=>(vs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Ge=(t,a,n)=>(vs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-CooTZX6k.js"),A=require("react");require("react-dom");function ba(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const pe=ba(A);var Me,Le,xe,we,ke,ms,Is,ft,Na=(ft=class extends s.Subscribable{constructor(a,n){super();qe(this,ke);qe(this,Me);qe(this,Le);qe(this,xe);qe(this,we);Ye(this,Me,a),this.setOptions(n),this.bindMethods(),Ge(this,ke,ms).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=oe(this,Me).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||oe(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:oe(this,xe),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=oe(this,xe))==null?void 0:r.state.status)==="pending"&&oe(this,xe).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=oe(this,xe))==null||a.removeObserver(this)}onMutationUpdate(a){Ge(this,ke,ms).call(this),Ge(this,ke,Is).call(this,a)}getCurrentResult(){return oe(this,Le)}reset(){var a;(a=oe(this,xe))==null||a.removeObserver(this),Ye(this,xe,void 0),Ge(this,ke,ms).call(this),Ge(this,ke,Is).call(this)}mutate(a,n){var r;return Ye(this,we,n),(r=oe(this,xe))==null||r.removeObserver(this),Ye(this,xe,oe(this,Me).getMutationCache().build(oe(this,Me),this.options)),oe(this,xe).addObserver(this),oe(this,xe).execute(a)}},Me=new WeakMap,Le=new WeakMap,xe=new WeakMap,we=new WeakMap,ke=new WeakSet,ms=function(){var n;const a=((n=oe(this,xe))==null?void 0:n.state)??s.getDefaultState();Ye(this,Le,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Is=function(a){s.notifyManager.batch(()=>{var n,r,l,o,c,i,d,u;if(oe(this,we)&&this.hasListeners()){const m=oe(this,Le).variables,h=oe(this,Le).context;(a==null?void 0:a.type)==="success"?((r=(n=oe(this,we)).onSuccess)==null||r.call(n,a.data,m,h),(o=(l=oe(this,we)).onSettled)==null||o.call(l,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=oe(this,we)).onError)==null||i.call(c,a.error,m,h),(u=(d=oe(this,we)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(oe(this,Le))})})},ft);function Be(t,a){const n=s.useQueryClient(),[r]=pe.useState(()=>new Na(n,t));pe.useEffect(()=>{r.setOptions(t)},[r,t]);const l=pe.useSyncExternalStore(pe.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=pe.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -362,4 +362,4 @@ ${C.joinType} JOIN ${I.name}
362
362
  FROM ${g.name}`;return f.forEach(p=>{const j=o.find(T=>T.name===p.target.name);if(!j)return;const x=p.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const R=T.keys.filter(b=>{var w,v,D,C;return((w=b.source)==null?void 0:w.name)&&((v=b.target)==null?void 0:v.name)&&((D=b.source)==null?void 0:D.entityName)&&((C=b.target)==null?void 0:C.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return R.length>1?`(${R.join(` ${T.operator} `)})`:R[0]}).filter(Boolean),N=x.length>1?x.join(" OR "):x[0]||"condition_here";y+=`
363
363
  ${p.joinType} JOIN ${j.name}
364
364
  ON ${N}`}),y};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Jl,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(ut,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(ut,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Zl({open:t,onOpenChange:a}){const[n,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(N=>N.name===p.name&&N.type===p.type)?j.filter(N=>!(N.name===p.name&&N.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(n.length===0)return;const p=n[0],j=p.connectionId||"",x=p.connectionType||"",T=n.some(b=>b.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:x,mode:T,selectedEntities:n}),a(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(gn,{className:"h-4 w-4"});case"model":return e.jsx(Fa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},y=p=>n.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",y(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:y(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function eo({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function so({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function to({isVisible:t,onToggleVisibility:a}){const[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(f=>f.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:y=>{y.stopPropagation();const p=h.selectedEntities.filter(j=>!(j.name===f.name&&j.type===f.type));u({...m,...d,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(eo,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(so,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(Xl,{})]})]}),e.jsx(Ql,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(Zl,{open:l,onOpenChange:o})]})}const ao="chart-selector-standard-first";function no(){const[t,a]=s.useLocalStorageState(ao,!0);return{standardFirst:t,updatePreference:a}}const mt=({pluginVisual:t,index:a,onSelect:n})=>{const r=js(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ht=["default","standardPlugin","customPlugin"];function ro({selectedChart:t,onChartChange:a}){var R;const[n,r]=A.useState(!1),{data:l}=Kt();no();const c=((R=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:R.url)||"";Ps(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,y]=s.useLocalStorageState("chart-section-active",null),p=A.useMemo(()=>g?[g,...ht.filter(b=>b!==g)]:ht,[g]);function j(b){m(null),d({}),i(b),["custom","text","map"].includes(b)&&(u(!0),f(void 0)),a(b),r(!1)}function x(b){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),a("custom"),r(!1)}const N=()=>{var w;if(t==="custom"){const v=s.useEditorStore.getState().card;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.componentName)||"Custom Visual"}const b=s.chartTypes.find(v=>v.id===t);return(b==null?void 0:b.label)||"Select chart type"},T=()=>{var w,v;if(t==="custom"){const D=s.useEditorStore.getState().card,C=(w=D==null?void 0:D.customCardPreferences)==null?void 0:w.icon,I=(v=D==null?void 0:D.customCardPreferences)==null?void 0:v.componentName;if(C&&I)return e.jsx(lo,{icon:C,componentName:I});if(I){const S=s.getAutoDetectedChartIcon(I);if(S)return S}return e.jsx(es,{className:"h-4 w-4"})}const b=s.chartTypes.find(D=>D.id===t);if(b){const D=b.icon;return e.jsx(D,{className:"h-4 w-4"})}return e.jsx(es,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:N()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(b=>{if(b==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:w=>y(w?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(w=>{const v=w.icon;return e.jsx(s.CommandItem,{value:`${w.label} ${w.id} chart graph visualization`,onSelect:()=>j(w.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:w.label})]})},w.id)})},"default");if(b==="standardPlugin"){const w=l.filter(v=>v.pluginType==="standard");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>y(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.filter(v=>v.componentType==="chart").map((v,D)=>e.jsx(mt,{pluginVisual:v,index:D,onSelect:()=>x(v)},`${v.url}-${v.name}-${D}`))},"standardPlugin"):null}if(b==="customPlugin"){const w=l.filter(v=>v.pluginType==="custom");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>y(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.map((v,D)=>e.jsx(mt,{pluginVisual:v,index:D,onSelect:()=>x(v)},`${v.url}-${v.name}-${D}`))},"customPlugin"):null}return null})]})]})})]})})}const lo=({icon:t,componentName:a})=>{const n=js(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(es,{className:"h-4 w-4"})},oo=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function io({selectedChart:t,onChartChange:a}){var l;const n=s.useEditorStore(o=>o.card),r=((l=n==null?void 0:n.config)==null?void 0:l.pivotByColumns)&&n.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:oo.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Hs=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})};function co({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function uo({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[l]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],g)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:y=>o(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?m(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:y=>i(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?m(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function mo({field:t,searchQuery:a="",limit:n=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(d=>d.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,a,n],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},u={connection_id:o.connectionId,cardConfig:d,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",u);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",u);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const y=g[h]||g[t.alias||h]||g[t.label];return{id:y||"",value:y||"",label:String(y||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function ho({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:o}){var T,R;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,f]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=n.filter(b=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(D=>D.field.id===b.id))&&b.label.toLowerCase().includes(u.toLowerCase())}),y=b=>{f({...h,field:b}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const b={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(c){const v=((r==null?void 0:r.conditions)||[]).map(D=>D.id===l.id?b:D);w={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,b],groups:[]}}o(w),a(!1)}},j=()=>{if(!c||!l)return;const b=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(b.length>0){const w={...r,conditions:b};o(w)}else o(void 0);a(!1)},x=b=>{f({...h,selectedValues:b})},N=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(f({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(T=h.field)==null?void 0:T.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(b=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[b.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(b.value)?`${b.value.length} values`:String(b.value)})]},b.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:b=>m(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(b=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>y(b),children:[e.jsx(Hs,{dataType:s.getDataType(b.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:b.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[b.entityName,".",b.name]})]})]},b.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(xo,{field:h.field,selectedValues:h.selectedValues,onValuesChange:x,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:N,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function xo({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=mo({field:t,searchQuery:l,limit:500}),u=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,m=f=>{const g=a.includes(f);n(g?a.filter(y=>y!==f):[...a,f])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(f.value),children:[e.jsx(s.Checkbox,{checked:a.includes(f.value),onCheckedChange:()=>m(f.value)}),e.jsx(ys,{className:"text-sm",children:f.label})]},f.id))})]})]})}function po({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Ws,Js,Xs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(Y=>Y.card),{updateLabel:y,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:x,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:R,handleKpiComparisonTypeChange:b,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:C}=Gs(g),[I,S]=A.useState(!1),[B,k]=A.useState(!1),[E,M]=A.useState(null),[O,L]=A.useState(t.dateFormat||"YYYY-MM-DD"),[F,z]=A.useState(t.customFormat||""),[H,U]=A.useState(!!t.customFormat),[Z,X]=A.useState(t.granularity||"day"),[q,G]=A.useState(t.aliasTemplate||""),[$,J]=A.useState(t.valueAliases||{}),[V,P]=A.useState((Ws=t.parameters)==null?void 0:Ws.filters),K=Y=>{Y==="custom"?U(!0):(U(!1),L(Y),a==="groupBy"&&j(n,Y,""))},te=Y=>{z(Y),a==="groupBy"&&j(n,"custom",Y)},_=Y=>{var he;X(Y);const ce=(he=se(Y)[0])==null?void 0:he.value;ce&&!H&&(L(ce),a==="groupBy"&&j(n,ce,"")),a==="groupBy"&&x(n,Y)},ee=Y=>{G(Y),a==="metrics"&&N(n,Y)},re=Y=>{J(Y),a==="metrics"&&T(n,Y)},Q=Y=>{y(a,n,Y)},W=Y=>{var ie;if(P(Y),a==="metrics"){const ce={...t,parameters:{...t.parameters,filters:Y}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[n]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}k(!1)},le=()=>{R(a,n)},de={transform:s.CSS.Transform.toString(m),transition:h},Se=s.getDataType(t.dataType),ve=Se==="date",fe=c==="kpi",se=Y=>{switch(Y){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ae=se(Z),ue=a!=="pivotBy",be=ve&&a==="groupBy",ns=!fe&&ve&&a==="groupBy",rs=fe&&ve&&a==="groupBy",ls=fe&&a==="metrics"&&((Js=g.config)==null?void 0:Js.comparisonType)==="target",Je=a==="metrics",Ie=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Y=>{Y.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),me=()=>ue?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(De,{value:t.label??"",onSave:Q,placeholder:"Display label...",type:"text"})]}):null,Ks=()=>be?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:Z,onValueChange:_,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(Y=>e.jsx(s.SelectItem,{className:"text-xs",value:Y,children:s.toTitleCase(Y)},Y))})]})]}):null,xa=()=>ns?e.jsxs(e.Fragment,{children:[Ks(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:H?"custom":O,onValueChange:K,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ae.map(Y=>e.jsx(s.SelectItem,{className:"text-xs",value:Y.value,children:Y.label},Y.value))})]}),H&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:F,onChange:Y=>{Y.stopPropagation(),te(Y.target.value)},onClick:Y=>Y.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,pa=()=>{var Y,ie,ce,he,Ae;return rs?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((Y=g.config)==null?void 0:Y.comparisonType)||"none",onValueChange:b,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=g.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:w})]})}),((ce=g.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((he=g.config)==null?void 0:he.trendlineWindow)||30,onChange:os=>{const va=parseInt(os.target.value)||30;v(va)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((Ae=g.config)==null?void 0:Ae.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},fa=()=>{var Y,ie;return ls?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(De,{value:((Y=g.config)==null?void 0:Y.targetValue)!==void 0&&((ie=g.config)==null?void 0:ie.targetValue)!==null?String(g.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?C(Number(ce)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},ga=()=>Je?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:Y=>{p(n,Y)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(V==null?void 0:V.conditions)&&V.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:V.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(Y),k(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var he;ie.stopPropagation();const ce=V.conditions.filter(Ae=>Ae.id!==Y.id);if(ce.length>0){const Ae={...V,conditions:ce};W(Ae)}else if(P(void 0),a==="metrics"){const Ae={...t,parameters:{...t.parameters,filters:void 0}},os=[...((he=g.config)==null?void 0:he.metricColumns)||[]];os[n]=Ae,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:os})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),k(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(da,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(co,{aliasTemplate:q,onAliasTemplateChange:ee}),e.jsx(uo,{valueAliases:$,onValueAliasesChange:re})]})]}):null,{columns:ja=[]}=s.useColumns(),ya=(V==null?void 0:V.conditions)&&V.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:de,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Hs,{dataType:Se}),e.jsx(ys,{className:s.cn("w-[140px] flex-1 text-sm",ya&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((Xs=V==null?void 0:V.conditions)==null?void 0:Xs.length)&&!I&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:V.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:V.conditions.map(Y=>e.jsxs("div",{children:[Y.field.label,":"," ",Array.isArray(Y.value)?`${Y.value.length} values`:String(Y.value)]},Y.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),S(!I)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${I?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),le()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),I&&e.jsxs("div",{className:"space-y-3",children:[Ie(),me(),c==="kpi"&&Ks(),xa(),pa(),fa(),ga()]})]}),B&&e.jsx(ho,{open:B,onOpenChange:Y=>{k(Y),Y||M(null)},availableFields:ja,existingFilters:V,editingCondition:E,onSave:Y=>{var ie;if(Y)W(Y);else if(P(void 0),a==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[n]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}M(null)}})]})}function fo({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function ds({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(y=>y.card),m=s.useEditorStore(y=>y.card.type),h=a.length>0,f=(y,p)=>{var x;!((x=u.config)!=null&&x.sortByColumns)||u.config.sortByColumns.findIndex(N=>N.id===y)===-1||d(u.id,y,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),g&&e.jsx(fo,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((y,p)=>{const x=y.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(po,{field:y,zone:t,index:p,sortDirection:x,onSortDirectionChange:N=>f(y.id,N),hasPivotColumns:o,cardType:m})})},y.id)})})})})]})}const xt=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],go=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Es({value:t,onChange:a,label:n}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=xt.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:xt[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${n}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:go.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(na,{color:i(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const us={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
365
- Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function jo(){var i,d,u,m,h,f,g,y,p,j;const t=s.useEditorStore(x=>x.card),{setCardPreferences:a}=s.useEditorActions(),n=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(n.length>=2&&r.length===0||n.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=x=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...x}}};a(N)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(us).map(([x,N])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:N.label},x))})]}),(()=>{var N,T,R;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=us[x])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=us[x])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=us[x])==null?void 0:R.example]})]})})()]}),e.jsx(qs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Es,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(Es,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(Es,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function yo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(qs,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function vo({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(y=>{var p;return((p=y.card.customCardPreferences)==null?void 0:p.url)&&y.card.type==="custom"}),o=s.useEditorStore(y=>y.card),c=o==null?void 0:o.type,i=t.length>0||n.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel"].includes(c),h=d&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ds,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(ds,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ds,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0}),u&&e.jsx(ds,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(yo,{}),e.jsx(jo,{}),e.jsx(ra,{}),e.jsx(la,{}),e.jsx(oa,{}),e.jsx(ia,{})]})})]})]})}function bo({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(ro,{selectedChart:t,onChartChange:a}),e.jsx(io,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(gs,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(vo,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function No({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(b=>b.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=b=>{const w=v=>{if(v.id===b){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},m=b=>{const w=v=>{if(v.id===b){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},h=(b,w)=>{const v=D=>D.id===b?{...D,conditions:D.conditions.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},f=(b,w)=>{const v=D=>D.id===b?{...D,groups:D.groups.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},g=(b,w,v,D)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=I=>I.id===b?{...I,conditions:I.conditions.map(S=>S.id===w?{...S,[v]:D}:S)}:{...I,groups:I.groups.map(C)};r(C(n))},y=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:C.conditions.map(I=>I.id===w?{...I,...v}:I)}:{...C,groups:C.groups.map(D)};r(D(n))},p=(b,w)=>{const v=D=>D.id===b?{...D,logicalOperator:w}:{...D,groups:D.groups.map(v)};r(v(n))},j=(b,w)=>{const v=D=>D.id===b?{...D,negate:w}:{...D,groups:D.groups.map(v)};r(v(n))},x=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:s.arrayMove(C.conditions,w,v)}:{...C,groups:C.groups.map(D)};r(D(n))},N=(b,w,v)=>{const D=C=>C.id===b?{...C,groups:s.arrayMove(C.groups,w,v)}:{...C,groups:C.groups.map(D)};r(D(n))},T=b=>{if(!b||b.conditions.length===0&&b.groups.length===0)return"-- No filters defined";const w=D=>{let C="";typeof D.field=="object"?C=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:C=String(D.field);const I=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(S)&&S.length===2){const B=S[0]?`'${S[0]}'`:"NULL",k=S[1]?`'${S[1]}'`:"NULL";return`${C} BETWEEN ${B} AND ${k}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(S)){const B=S.map(k=>k?`'${k}'`:"NULL").join(", ");return`${C} ${I} (${B})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(D.operator)){let B=[];Array.isArray(S)?B=S.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof S=="string"?B=S.split(",").map(k=>{const E=k.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(B=[String(S)]),S=`(${B.join(", ")})`}switch(I){case"contains":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${C} LIKE '${S.replace(/'/g,"")}%'`:`${C} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${I} ${S}`}},v=D=>{const C=D.conditions.map(w),I=D.groups.map(E=>v(E)),S=[...C,...I].filter(Boolean);if(S.length===0)return"";const B=S.join(` ${D.logicalOperator} `),k=S.length>1?`(${B})`:B;return D.negate?`NOT ${k}`:k};return v(b)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:y,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:x,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:R}}function Co({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const So=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wo=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Do({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=wo(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Co,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[So(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${d}-${m}`))},d))})]})})]})}function Qs(t){var y;const a=s.useEditorStore(p=>p.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},u=((y=a.dataSource)==null?void 0:y.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(p=>({label:p.value||"BLANK",value:p.value||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function ko({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=pe.useState(!1),{filterValues:i}=Qs(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function To({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Qs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Eo({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),i=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Io=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Lo=["=","!=","isNull","isNotNull"],Ro=["between","isNull","isNotNull"],Oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function pt(t){return Oo[t]||s.titleCase(t)}function Fo(t){switch(t){case"string":return Ao;case"number":return Mo;case"boolean":return Lo;case"date":return Ro;default:return Io}}function ma({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:y}=s.useSortable({id:t.id}),{isPending:p,error:j}=Qs(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(n,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:t.field,onValueChange:N=>{const T=N,R=s.getDataType(T.dataType)==="date";d(n,t.id,{field:T,value:"",operator:R?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(n,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?d(n,t.id,{operator:N,value:null}):d(n,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?pt(t.operator):""})}),e.jsx(s.SelectContent,{children:Fo(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:pt(N)},N))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(n,t.id,{value:N}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:N=>d(n,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(To,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(n,t.id,{value:N}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:N=>d(n,t.id,{value:N==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Eo,{value:t.value,operator:t.operator,onChange:N=>d(n,t.id,{value:N}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(n,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bo({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:y,updateConditionFields:p}){const{attributes:j,listeners:x,setNodeRef:N,transform:T,transition:R,isDragging:b}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(T),transition:R},v=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id){const B=t.conditions.findIndex(E=>E.id===I.id),k=t.conditions.findIndex(E=>E.id===S.id);B!==-1&&k!==-1&&u(t.id,B,k)}},D=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id&&n){const B=t.groups.findIndex(E=>E.id===I.id),k=t.groups.findIndex(E=>E.id===S.id);B!==-1&&k!==-1&&m(n,B,k)}};return e.jsxs("div",{ref:N,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${b?"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",{...j,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,I)=>e.jsx(ma,{condition:C,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>y(C,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Po({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:y,updateGroupNegate:p,reorderConditions:j,reorderGroups:x,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:R}=No({initialFilters:t,availableFields:a}),b=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=A.useState(!1),D=(S,B,k)=>{const E=M=>M.id===S?{...M,conditions:M.conditions.map(O=>O.id===B?{...O,field:k,dataType:k.dataType}:O)}:{...M,groups:M.groups.map(E)};R(E(o))},C=(S,B=0,k)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:O}=E;if(O&&M.id!==O.id){const L=S.conditions.findIndex(z=>z.id===M.id),F=S.conditions.findIndex(z=>z.id===O.id);L!==-1&&F!==-1&&j(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,M)=>e.jsx(ma,{condition:E,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:y,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:O}=E;if(O&&M.id!==O.id){const L=S.groups.findIndex(z=>z.id===M.id),F=S.groups.findIndex(z=>z.id===O.id);L!==-1&&F!==-1&&x(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>C(E,B+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Bo,{group:S,depth:B,parentGroupId:k,onUpdateGroupOperator:y,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:x,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:C,updateConditionFields:g},S.id),I=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:w,onCheckedChange:S=>v(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),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:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(T?o:null),children:"Apply Filters"})]})]})}function zo({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Po,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Vo({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(y=>y.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(y=>y.startsWith("card-")?null:y.startsWith("source-")||a.find(p=>p.id===y)?"source":n("groupBy").find(p=>p.id===y)?"groupBy":n("metrics").find(p=>p.id===y)?"metrics":n("pivotBy").find(p=>p.id===y)?"pivotBy":n("sortBy").find(p=>p.id===y)?"sortBy":null,[a,n]),m=A.useCallback(y=>{o(y.active.id)},[]),h=A.useCallback(y=>{const{active:p,over:j}=y;if(!j||!t){o(null);return}const x=p.id,N=j.id,T=u(x),R=u(N)||N;if(R==="sortBy"){if(T==="source"){const b=a.find(v=>v.id===x);if(!b){o(null);return}if(!(n("groupBy").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName)||n("metrics").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&R==="sortBy"){const b=[...a].find(D=>D.id===x);if(!b){o(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(b,w)){o(null);return}const v=s.getNewField(b,"sortBy",w);o(null),r("sortBy",[...w,v]);return}if(T==="source"&&R!=="source"&&R!=="sortBy"){const b=[...a].find(C=>C.id===x);if(!b){o(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const C=w[0].qualifiedEntityName;if(!C){o(null);return}if(C!==b.qualifiedEntityName&&b.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,b.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=n(R);if(s.fieldAlreadyExists(b,v)){o(null);return}const D=s.getNewField(b,R,v);o(null),r(R,[...v,D]);return}if(T&&R&&T!=="source"&&R!=="source"&&T!==R){const b=n(T),w=n(R),v=b.find(I=>I.id===x);if(!v){o(null);return}const D=s.getNewField(v,R,w);if(o(null),R==="sortBy"){s.fieldAlreadyExists(v,w)||r(R,[...w,D]);return}const C=b.filter(I=>I.id!==x);r(T,C),r(R,[...w,D]);return}if(T&&R&&T===R&&T!=="source"){const b=n(T),w=b.findIndex(D=>D.id===x),v=b.findIndex(D=>D.id===N);if(w!==v){const D=s.arrayMove(b,w,v);r(T,D)}}o(null)},[t,a,n,r,u,i]),f=l?d.find(y=>y.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function _o({dashboardFilterCount:t=0,cardFilterCount:a=0,clickFilterCount:n=0,onClick:r,className:l,showIcon:o=!0}){const c=t+a+n,i=c>0,d=t>0,u=a>0,m=n>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[a," Card filter",a!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[n," Click filter",n!==1?"s":""]})]})]})})]})}):f}function Uo({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:u}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),y=s.useManagementStore(x=>x.selectedVisual),p=(y==null?void 0:y.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx(Us,{}),n&&!p&&e.jsx(_s,{variant:"default"}),p&&e.jsx(Mr,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function $o({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Info"})]})})}const qo=[{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 Yo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:qo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Go({isOpen:t,onClose:a}){const n=At(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ho(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{currentUser:n}=s.useCurrentUserInfo(),r=Be({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...l,user:n,tokenContext:a},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function Qo(t,a,n){return{category:t,userMessage:n,systemState:a,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function Ko({open:t,onOpenChange:a,feedbackData:n}){var p,j,x,N,T,R;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=Ho(),f=()=>{const b={...n,userMessage:r.trim()||void 0};i(b)},g=()=>{l(""),c(!1),h(),a(!1)},y={category:n.category,error:{message:(p=n.systemState)==null?void 0:p.errorMessage,sql:(j=n.systemState)==null?void 0:j.generatedSql,errorSql:(x=n.systemState)==null?void 0:x.errorSql},cardConfig:(N=n.systemState)==null?void 0:N.cardConfig,dataSource:(T=n.systemState)==null?void 0:T.dataSource,filters:(R=n.systemState)==null?void 0:R.dashboardFilters,metadata:n.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:b=>l(b.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(y,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(Ma,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var ha=(t=>(t.QUERY_GENERATION="query-generation",t))(ha||{});function Wo({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var $;const g=s.useEditorStore(J=>J.card),y=s.useDashboardStore(J=>J.filterValues),p=(y==null?void 0:y.length)||0,{updateCardConfig:j,setCard:x,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:R}=s.useDashboardActions(),[b,w]=A.useState(null),v=s.useEditorStore(J=>J.showAIDialog),[D,C]=A.useState(!1),[I,S]=A.useState(!1),[B,k]=A.useState(null),{isConsoleMode:E}=s.useDashboardPreferences(),M=s.useEditorStore(J=>{var V;return((V=J.card.customCardPreferences)==null?void 0:V.url)&&J.card.type==="custom"}),{data:O,errorMessage:L,isLoading:F,isFetching:z,errorSql:H,pagination:U}=s.useDashboardCardQuery(u),Z=(J,V)=>{const P={...u,paginationConfig:{page:J+1,pageSize:V}};x(P),N(P)};function X(){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(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(y||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const q=J=>{if(!g.config)return;if(!J.length){j(g.id,{...g.config,sortByColumns:[]});return}const V=g.config,P=J.map(({id:K,desc:te})=>{var Q,W;const _=(Q=V.metricColumns)==null?void 0:Q.find(le=>le.label===K),ee=(W=V.groupByColumns)==null?void 0:W.find(le=>le.label===K),re=_||ee;return re?{id:s.getFieldId("sortBy",re),name:re.name,dataType:re.dataType,label:re.label,qualifiedEntityName:re.qualifiedEntityName,entityId:re.entityId,entityName:re.entityName,entityType:re.entityType,role:"sortby",direction:te?"desc":"asc"}:null}).filter(K=>K!==null);j(g.id,{...V,sortByColumns:P})},G=A.useMemo(()=>{var J,V;return(V=(J=g.config)==null?void 0:J.sortByColumns)==null?void 0:V.map(P=>({id:P.label,desc:P.direction==="desc"}))},[($=g.config)==null?void 0:$.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Uo,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&X(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(Jt,{variant:"outline"}),e.jsx($o,{activeView:t,onViewChange:a}),i&&e.jsx(_o,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(Yo,{})}),v&&e.jsx(gs,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Xt,{})})]}),!D&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>C(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Zt,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:u,data:(O==null?void 0:O.records)||[],paginationMetadata:U,onPaginationChange:Z,isLoading:F||z,onSortChange:q,sortState:G})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[E&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:J=>{const V=s.sanitizeCardId(J);if(!V){w("Card ID cannot be empty");return}const P=R(g.id,V);if(P.success){T(V);const K={...g,id:V};x(K),N(K),w(null),s.ue.success("Card ID updated successfully")}else w(P.error||"Failed to update Card ID"),s.ue.error(P.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),b&&e.jsx("p",{className:"text-xs text-destructive",children:b})]}),L||H?e.jsx($t,{error:L,errorSql:H,onSendFeedback:()=>{const J=Qo(ha.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:y,errorMessage:L,errorSql:H,generatedSql:O==null?void 0:O.sql});k(J),S(!0)}}):e.jsxs(e.Fragment,{children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(qt,{sql:O==null?void 0:O.sql,error:L,errorSql:H})]})]})})]}),e.jsx(Go,{isOpen:D,onClose:()=>C(!1)}),B&&e.jsx(Ko,{open:I,onOpenChange:S,feedbackData:B})]})]})}function Jo({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Hs,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Xo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Zo(){var X,q;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);A.useEffect(()=>Xo(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},y=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=G=>{m(G)},x=s.useEditorStore(G=>G.frame),N=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:T,removeCard:R,updateCard:b,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:D=[],isLoading:C,error:I}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=N,{getFieldsForContainer:k,setFieldsForContainer:E}=Gs(B),{activeField:M,handleDragStart:O,handleDragEnd:L}=Vo({activeCardId:x.activeCardId,sourceFields:D,getFieldsForContainer:k,setFieldsForContainer:E}),F=(G,$)=>{$&&v(G,$)},z=G=>{var $;b(G,{config:{...($=x.cards.find(J=>J.id===G))==null?void 0:$.config,filters:void 0}})},H=D,U=G=>{if(!G)return 0;let $=G.conditions.length;return G.groups.forEach(J=>{$+=U(J)}),$},Z=U(((X=B==null?void 0:B.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(to,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(bo,{selectedChart:h,onChartChange:j,groupByFields:k("groupBy"),pivotByFields:k("pivotBy"),metricsFields:k("metrics"),sortByFields:k("sortBy")}),e.jsx(Wo,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:g,onAdvancedToggle:y,onFiltersClick:p,filterCount:Z,activeCard:B,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:C,columnsError:I,getFieldsForContainer:k,cards:x.cards,activeCardId:x.activeCardId,addCard:T,setActiveCard:w})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),B&&e.jsx(zo,{cardId:B.id,filters:((q=B.config)==null?void 0:q.filters)||null,onFiltersChange:F,onClearFilters:z,availableFields:H,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Jo,{activeField:M||null})})]})}function ei({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:y}=wr();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,T;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function p(N){N<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ul,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(dt,{})})]})]})}function x(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Zo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(dt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:y,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):x()})}function si(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(ei,{onSave:l,onClose:o})})}function ti({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Te,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ue,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Aa,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function ai(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=$s();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ti,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function ni({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function ri(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=$s(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const N=s.getDataType(x.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},f=n==="all"?m:m.filter(x=>h(x)===n),g=m.filter(x=>h(x)==="dimensions").length,y=m.filter(x=>h(x)==="metrics").length,p=x=>{const N={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(N,"dashboard",x)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>a(x.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:y})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&n!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",n," fields found"]}),f.map(x=>{const N=l==null?void 0:l.some(T=>{var R;return T.title===x.name||((R=T.column)==null?void 0:R.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ni,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function li(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),a=s.useCurrentActiveCard(),n=a&&((r=a.dataSource)==null?void 0:r.selectedEntities)&&a.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:n?e.jsx(ri,{}):e.jsx(Ut,{type:"filter",ColumnsComponent:()=>e.jsx(ai,{})})})]})}function oi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function ii(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(oi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(li,{})})]})}function ci(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function di({showControls:t=!1,showFooter:a=!0,...n}){if(typeof window>"u")return null;const{preferences:r}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(ci,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(yr,{}),e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(si,{}),e.jsx(ii,{})]})]})]})})]})})}exports.DashboardPlus=di;exports.ResourceManagementPanel=Vt;exports.ScheduleDashboard=Ct;exports.SelectComponent=He;exports.cleanCard=Nt;exports.getDashbaordStateWithoutData=hs;
365
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function jo(){var i,d,u,m,h,f,g,y,p,j;const t=s.useEditorStore(x=>x.card),{setCardPreferences:a}=s.useEditorActions(),n=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(n.length>=2&&r.length===0||n.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=x=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...x}}};a(N)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(us).map(([x,N])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:N.label},x))})]}),(()=>{var N,T,R;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=us[x])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=us[x])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=us[x])==null?void 0:R.example]})]})})()]}),e.jsx(qs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Es,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(Es,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(Es,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function yo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(qs,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function vo({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(y=>{var p;return((p=y.card.customCardPreferences)==null?void 0:p.url)&&y.card.type==="custom"}),o=s.useEditorStore(y=>y.card),c=o==null?void 0:o.type,i=t.length>0||n.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel"].includes(c),h=d&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ds,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(ds,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ds,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0}),u&&e.jsx(ds,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(yo,{}),e.jsx(jo,{}),e.jsx(ra,{}),e.jsx(la,{}),e.jsx(oa,{}),e.jsx(ia,{})]})})]})]})}function bo({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(ro,{selectedChart:t,onChartChange:a}),e.jsx(io,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(gs,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(vo,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function No({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(b=>b.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=b=>{const w=v=>{if(v.id===b){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},m=b=>{const w=v=>{if(v.id===b){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(n))},h=(b,w)=>{const v=D=>D.id===b?{...D,conditions:D.conditions.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},f=(b,w)=>{const v=D=>D.id===b?{...D,groups:D.groups.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(n))},g=(b,w,v,D)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=I=>I.id===b?{...I,conditions:I.conditions.map(S=>S.id===w?{...S,[v]:D}:S)}:{...I,groups:I.groups.map(C)};r(C(n))},y=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:C.conditions.map(I=>I.id===w?{...I,...v}:I)}:{...C,groups:C.groups.map(D)};r(D(n))},p=(b,w)=>{const v=D=>D.id===b?{...D,logicalOperator:w}:{...D,groups:D.groups.map(v)};r(v(n))},j=(b,w)=>{const v=D=>D.id===b?{...D,negate:w}:{...D,groups:D.groups.map(v)};r(v(n))},x=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:s.arrayMove(C.conditions,w,v)}:{...C,groups:C.groups.map(D)};r(D(n))},N=(b,w,v)=>{const D=C=>C.id===b?{...C,groups:s.arrayMove(C.groups,w,v)}:{...C,groups:C.groups.map(D)};r(D(n))},T=b=>{if(!b||b.conditions.length===0&&b.groups.length===0)return"-- No filters defined";const w=D=>{let C="";typeof D.field=="object"?C=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:C=String(D.field);const I=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(S)&&S.length===2){const B=S[0]?`'${S[0]}'`:"NULL",k=S[1]?`'${S[1]}'`:"NULL";return`${C} BETWEEN ${B} AND ${k}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(S)){const B=S.map(k=>k?`'${k}'`:"NULL").join(", ");return`${C} ${I} (${B})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(D.operator)){let B=[];Array.isArray(S)?B=S.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof S=="string"?B=S.split(",").map(k=>{const E=k.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(B=[String(S)]),S=`(${B.join(", ")})`}switch(I){case"contains":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${C} LIKE '${S.replace(/'/g,"")}%'`:`${C} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${I} ${S}`}},v=D=>{const C=D.conditions.map(w),I=D.groups.map(E=>v(E)),S=[...C,...I].filter(Boolean);if(S.length===0)return"";const B=S.join(` ${D.logicalOperator} `),k=S.length>1?`(${B})`:B;return D.negate?`NOT ${k}`:k};return v(b)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:y,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:x,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:R}}function Co({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const So=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wo=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Do({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=wo(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Co,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[So(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${d}-${m}`))},d))})]})})]})}function Qs(t){var y;const a=s.useEditorStore(p=>p.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},u=((y=a.dataSource)==null?void 0:y.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(p=>({label:p.value||"BLANK",value:p.value||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function ko({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=pe.useState(!1),{filterValues:i}=Qs(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function To({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Qs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Eo({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),i=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Io=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Lo=["=","!=","isNull","isNotNull"],Ro=["between","isNull","isNotNull"],Oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function pt(t){return Oo[t]||s.titleCase(t)}function Fo(t){switch(t){case"string":return Ao;case"number":return Mo;case"boolean":return Lo;case"date":return Ro;default:return Io}}function ma({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:y}=s.useSortable({id:t.id}),{isPending:p,error:j}=Qs(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(n,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:t.field,onValueChange:N=>{const T=N,R=s.getDataType(T.dataType)==="date";d(n,t.id,{field:T,value:"",operator:R?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(n,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?d(n,t.id,{operator:N,value:null}):d(n,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?pt(t.operator):""})}),e.jsx(s.SelectContent,{children:Fo(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:pt(N)},N))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(n,t.id,{value:N}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:N=>d(n,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(To,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(n,t.id,{value:N}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:N=>d(n,t.id,{value:N==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Eo,{value:t.value,operator:t.operator,onChange:N=>d(n,t.id,{value:N}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(n,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bo({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:y,updateConditionFields:p}){const{attributes:j,listeners:x,setNodeRef:N,transform:T,transition:R,isDragging:b}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(T),transition:R},v=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id){const B=t.conditions.findIndex(E=>E.id===I.id),k=t.conditions.findIndex(E=>E.id===S.id);B!==-1&&k!==-1&&u(t.id,B,k)}},D=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id&&n){const B=t.groups.findIndex(E=>E.id===I.id),k=t.groups.findIndex(E=>E.id===S.id);B!==-1&&k!==-1&&m(n,B,k)}};return e.jsxs("div",{ref:N,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${b?"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",{...j,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,I)=>e.jsx(ma,{condition:C,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>y(C,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Po({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:y,updateGroupNegate:p,reorderConditions:j,reorderGroups:x,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:R}=No({initialFilters:t,availableFields:a}),b=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=A.useState(!1),D=(S,B,k)=>{const E=M=>M.id===S?{...M,conditions:M.conditions.map(O=>O.id===B?{...O,field:k,dataType:k.dataType}:O)}:{...M,groups:M.groups.map(E)};R(E(o))},C=(S,B=0,k)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:O}=E;if(O&&M.id!==O.id){const L=S.conditions.findIndex(z=>z.id===M.id),F=S.conditions.findIndex(z=>z.id===O.id);L!==-1&&F!==-1&&j(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,M)=>e.jsx(ma,{condition:E,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:y,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:O}=E;if(O&&M.id!==O.id){const L=S.groups.findIndex(z=>z.id===M.id),F=S.groups.findIndex(z=>z.id===O.id);L!==-1&&F!==-1&&x(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>C(E,B+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Bo,{group:S,depth:B,parentGroupId:k,onUpdateGroupOperator:y,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:x,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:C,updateConditionFields:g},S.id),I=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:w,onCheckedChange:S=>v(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),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:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(T?o:null),children:"Apply Filters"})]})]})}function zo({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Po,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Vo({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(y=>y.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(y=>y.startsWith("card-")?null:y.startsWith("source-")||a.find(p=>p.id===y)?"source":n("groupBy").find(p=>p.id===y)?"groupBy":n("metrics").find(p=>p.id===y)?"metrics":n("pivotBy").find(p=>p.id===y)?"pivotBy":n("sortBy").find(p=>p.id===y)?"sortBy":null,[a,n]),m=A.useCallback(y=>{o(y.active.id)},[]),h=A.useCallback(y=>{const{active:p,over:j}=y;if(!j||!t){o(null);return}const x=p.id,N=j.id,T=u(x),R=u(N)||N;if(R==="sortBy"){if(T==="source"){const b=a.find(v=>v.id===x);if(!b){o(null);return}if(!(n("groupBy").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName)||n("metrics").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&R==="sortBy"){const b=[...a].find(D=>D.id===x);if(!b){o(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(b,w)){o(null);return}const v=s.getNewField(b,"sortBy",w);o(null),r("sortBy",[...w,v]);return}if(T==="source"&&R!=="source"&&R!=="sortBy"){const b=[...a].find(C=>C.id===x);if(!b){o(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const C=w[0].qualifiedEntityName;if(!C){o(null);return}if(C!==b.qualifiedEntityName&&b.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,b.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=n(R);if(s.fieldAlreadyExists(b,v)){o(null);return}const D=s.getNewField(b,R,v);o(null),r(R,[...v,D]);return}if(T&&R&&T!=="source"&&R!=="source"&&T!==R){const b=n(T),w=n(R),v=b.find(I=>I.id===x);if(!v){o(null);return}const D=s.getNewField(v,R,w);if(o(null),R==="sortBy"){s.fieldAlreadyExists(v,w)||r(R,[...w,D]);return}const C=b.filter(I=>I.id!==x);r(T,C),r(R,[...w,D]);return}if(T&&R&&T===R&&T!=="source"){const b=n(T),w=b.findIndex(D=>D.id===x),v=b.findIndex(D=>D.id===N);if(w!==v){const D=s.arrayMove(b,w,v);r(T,D)}}o(null)},[t,a,n,r,u,i]),f=l?d.find(y=>y.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function _o({dashboardFilterCount:t=0,cardFilterCount:a=0,clickFilterCount:n=0,onClick:r,className:l,showIcon:o=!0}){const c=t+a+n,i=c>0,d=t>0,u=a>0,m=n>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[a," Card filter",a!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[n," Click filter",n!==1?"s":""]})]})]})})]})}):f}function Uo({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:u}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),y=s.useManagementStore(x=>x.selectedVisual),p=(y==null?void 0:y.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Us,{}),n&&!p&&e.jsx(_s,{variant:"default"}),p&&e.jsx(Mr,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function $o({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Info"})]})})}const qo=[{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 Yo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:qo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Go({isOpen:t,onClose:a}){const n=At(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ho(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{currentUser:n}=s.useCurrentUserInfo(),r=Be({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...l,user:n,tokenContext:a},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function Qo(t,a,n){return{category:t,userMessage:n,systemState:a,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function Ko({open:t,onOpenChange:a,feedbackData:n}){var p,j,x,N,T,R;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=Ho(),f=()=>{const b={...n,userMessage:r.trim()||void 0};i(b)},g=()=>{l(""),c(!1),h(),a(!1)},y={category:n.category,error:{message:(p=n.systemState)==null?void 0:p.errorMessage,sql:(j=n.systemState)==null?void 0:j.generatedSql,errorSql:(x=n.systemState)==null?void 0:x.errorSql},cardConfig:(N=n.systemState)==null?void 0:N.cardConfig,dataSource:(T=n.systemState)==null?void 0:T.dataSource,filters:(R=n.systemState)==null?void 0:R.dashboardFilters,metadata:n.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:b=>l(b.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(y,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(Ma,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var ha=(t=>(t.QUERY_GENERATION="query-generation",t))(ha||{});function Wo({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var $;const g=s.useEditorStore(J=>J.card),y=s.useDashboardStore(J=>J.filterValues),p=(y==null?void 0:y.length)||0,{updateCardConfig:j,setCard:x,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:R}=s.useDashboardActions(),[b,w]=A.useState(null),v=s.useEditorStore(J=>J.showAIDialog),[D,C]=A.useState(!1),[I,S]=A.useState(!1),[B,k]=A.useState(null),{isConsoleMode:E}=s.useDashboardPreferences(),M=s.useEditorStore(J=>{var V;return((V=J.card.customCardPreferences)==null?void 0:V.url)&&J.card.type==="custom"}),{data:O,errorMessage:L,isLoading:F,isFetching:z,errorSql:H,pagination:U}=s.useDashboardCardQuery(u),Z=(J,V)=>{const P={...u,paginationConfig:{page:J+1,pageSize:V}};x(P),N(P)};function X(){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(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(y||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const q=J=>{if(!g.config)return;if(!J.length){j(g.id,{...g.config,sortByColumns:[]});return}const V=g.config,P=J.map(({id:K,desc:te})=>{var Q,W;const _=(Q=V.metricColumns)==null?void 0:Q.find(le=>le.label===K),ee=(W=V.groupByColumns)==null?void 0:W.find(le=>le.label===K),re=_||ee;return re?{id:s.getFieldId("sortBy",re),name:re.name,dataType:re.dataType,label:re.label,qualifiedEntityName:re.qualifiedEntityName,entityId:re.entityId,entityName:re.entityName,entityType:re.entityType,role:"sortby",direction:te?"desc":"asc"}:null}).filter(K=>K!==null);j(g.id,{...V,sortByColumns:P})},G=A.useMemo(()=>{var J,V;return(V=(J=g.config)==null?void 0:J.sortByColumns)==null?void 0:V.map(P=>({id:P.label,desc:P.direction==="desc"}))},[($=g.config)==null?void 0:$.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Uo,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&X(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(Jt,{variant:"outline"}),e.jsx($o,{activeView:t,onViewChange:a}),i&&e.jsx(_o,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(Yo,{})}),v&&e.jsx(gs,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Xt,{})})]}),!D&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>C(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Zt,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:u,data:(O==null?void 0:O.records)||[],paginationMetadata:U,onPaginationChange:Z,isLoading:F||z,onSortChange:q,sortState:G})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[E&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:J=>{const V=s.sanitizeCardId(J);if(!V){w("Card ID cannot be empty");return}const P=R(g.id,V);if(P.success){T(V);const K={...g,id:V};x(K),N(K),w(null),s.ue.success("Card ID updated successfully")}else w(P.error||"Failed to update Card ID"),s.ue.error(P.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),b&&e.jsx("p",{className:"text-xs text-destructive",children:b})]}),L||H?e.jsx($t,{error:L,errorSql:H,onSendFeedback:()=>{const J=Qo(ha.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:y,errorMessage:L,errorSql:H,generatedSql:O==null?void 0:O.sql});k(J),S(!0)}}):e.jsxs(e.Fragment,{children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(qt,{sql:O==null?void 0:O.sql,error:L,errorSql:H})]})]})})]}),e.jsx(Go,{isOpen:D,onClose:()=>C(!1)}),B&&e.jsx(Ko,{open:I,onOpenChange:S,feedbackData:B})]})]})}function Jo({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Hs,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Xo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Zo(){var X,q;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);A.useEffect(()=>Xo(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},y=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=G=>{m(G)},x=s.useEditorStore(G=>G.frame),N=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:T,removeCard:R,updateCard:b,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:D=[],isLoading:C,error:I}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=N,{getFieldsForContainer:k,setFieldsForContainer:E}=Gs(B),{activeField:M,handleDragStart:O,handleDragEnd:L}=Vo({activeCardId:x.activeCardId,sourceFields:D,getFieldsForContainer:k,setFieldsForContainer:E}),F=(G,$)=>{$&&v(G,$)},z=G=>{var $;b(G,{config:{...($=x.cards.find(J=>J.id===G))==null?void 0:$.config,filters:void 0}})},H=D,U=G=>{if(!G)return 0;let $=G.conditions.length;return G.groups.forEach(J=>{$+=U(J)}),$},Z=U(((X=B==null?void 0:B.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(to,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(bo,{selectedChart:h,onChartChange:j,groupByFields:k("groupBy"),pivotByFields:k("pivotBy"),metricsFields:k("metrics"),sortByFields:k("sortBy")}),e.jsx(Wo,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:g,onAdvancedToggle:y,onFiltersClick:p,filterCount:Z,activeCard:B,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:C,columnsError:I,getFieldsForContainer:k,cards:x.cards,activeCardId:x.activeCardId,addCard:T,setActiveCard:w})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),B&&e.jsx(zo,{cardId:B.id,filters:((q=B.config)==null?void 0:q.filters)||null,onFiltersChange:F,onClearFilters:z,availableFields:H,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Jo,{activeField:M||null})})]})}function ei({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:y}=wr();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,T;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function p(N){N<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ul,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(dt,{})})]})]})}function x(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Zo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(dt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:y,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):x()})}function si(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(ei,{onSave:l,onClose:o})})}function ti({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Te,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ue,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Aa,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function ai(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=$s();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ti,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function ni({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ze,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function ri(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=$s(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const N=s.getDataType(x.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},f=n==="all"?m:m.filter(x=>h(x)===n),g=m.filter(x=>h(x)==="dimensions").length,y=m.filter(x=>h(x)==="metrics").length,p=x=>{const N={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(N,"dashboard",x)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>a(x.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:y})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&n!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",n," fields found"]}),f.map(x=>{const N=l==null?void 0:l.some(T=>{var R;return T.title===x.name||((R=T.column)==null?void 0:R.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ni,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function li(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),a=s.useCurrentActiveCard(),n=a&&((r=a.dataSource)==null?void 0:r.selectedEntities)&&a.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:n?e.jsx(ri,{}):e.jsx(Ut,{type:"filter",ColumnsComponent:()=>e.jsx(ai,{})})})]})}function oi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function ii(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(oi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(li,{})})]})}function ci(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function di({showControls:t=!1,showFooter:a=!0,...n}){if(typeof window>"u")return null;const{preferences:r}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(ci,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(yr,{}),e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(si,{}),e.jsx(ii,{})]})]})]})})]})})}exports.DashboardPlus=di;exports.ResourceManagementPanel=Vt;exports.ScheduleDashboard=Ct;exports.SelectComponent=He;exports.cleanCard=Nt;exports.getDashbaordStateWithoutData=hs;