react-semaphor 0.0.646 → 0.0.647

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.
@@ -337,4 +337,4 @@ ${y.joinType} JOIN ${O.name}
337
337
  FROM ${g.name}`;return x.forEach(p=>{const j=o.find(T=>T.name===p.target.name);if(!j)return;const f=p.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const I=T.keys.filter(w=>{var C,v,k,y;return((C=w.source)==null?void 0:C.name)&&((v=w.target)==null?void 0:v.name)&&((k=w.source)==null?void 0:k.entityName)&&((y=w.target)==null?void 0:y.entityName)}).map(w=>`${w.source.entityName}.${w.source.name} ${w.operator} ${w.target.entityName}.${w.target.name}`);return I.length>1?`(${I.join(` ${T.operator} `)})`:I[0]}).filter(Boolean),N=f.length>1?f.join(" OR "):f[0]||"condition_here";b+=`
338
338
  ${p.joinType} JOIN ${j.name}
339
339
  ON ${N}`}),b};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:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{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":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(gl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Ks,{open:r,onOpenChange:l,joinPlan:a,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 bl({open:t,onOpenChange:n}){const[a,r]=M.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];M.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(a.length===0)return;const p=a[0],j=p.connectionId||"",f=p.connectionType||"",T=a.some(w=>w.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:T,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ya,{className:"h-4 w-4"});case"model":return e.jsx(xa,{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"})}},x=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(".")},b=p=>a.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,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:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.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",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(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:x(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:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function vl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),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:n||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 yl({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((n,a)=>{const r=s.getEntityDetails(n),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(n)}),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-${n.type}-${n.name}-${a}`)})})]})})}function Nl({isVisible:t,onToggleVisibility:n}){const[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(x=>x.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:n,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,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((x,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(x),e.jsx("button",{onClick:b=>{b.stopPropagation();const p=h.selectedEntities.filter(j=>!(j.name===x.name&&j.type===x.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(vl,{entity:x})]},`${x.type}-${x.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(yl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(jl,{})]})]}),e.jsx(xl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(bl,{open:l,onOpenChange:o})]})}const Cl="chart-selector-standard-first";function Sl(){const[t,n]=s.useLocalStorageState(Cl,!0);return{standardFirst:t,updatePreference:n}}const Qs=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(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:a,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}-${n}`)},Js=["default","standardPlugin","customPlugin"];function wl({selectedChart:t,onChartChange:n}){var I;const[a,r]=M.useState(!1),{data:l}=wt();Sl();const c=((I=s.useEditorStore(w=>w.card).customCardPreferences)==null?void 0:I.url)||"";Ds(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(w=>w.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),p=M.useMemo(()=>g?[g,...Js.filter(w=>w!==g)]:Js,[g]);function j(w){m(null),d({}),i(w),["custom","map"].includes(w)&&(u(!0),x(void 0)),n(w),r(!1)}function f(w){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:w.url,componentName:w.name,icon:w.icon,pluginChartType:w.chartType}),x(void 0),n("custom"),r(!1)}const N=()=>{var C;if(t==="custom"){const v=s.useEditorStore.getState().card;return((C=v==null?void 0:v.customCardPreferences)==null?void 0:C.componentName)||"Custom Visual"}const w=s.chartTypes.find(v=>v.id===t);return(w==null?void 0:w.label)||"Select chart type"},T=()=>{var C,v;if(t==="custom"){const k=s.useEditorStore.getState().card,y=(C=k==null?void 0:k.customCardPreferences)==null?void 0:C.icon,O=(v=k==null?void 0:k.customCardPreferences)==null?void 0:v.componentName;if(y&&O)return e.jsx(Dl,{icon:y,componentName:O});if(O){const E=s.getAutoDetectedChartIcon(O);if(E)return E}return e.jsx(He,{className:"h-4 w-4"})}const w=s.chartTypes.find(k=>k.id===t);if(w){const k=w.icon;return e.jsx(k,{className:"h-4 w-4"})}return e.jsx(He,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,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(w=>{if(w==="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:C=>b(C?"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(C=>{const v=C.icon;return e.jsx(s.CommandItem,{value:`${C.label} ${C.id} chart graph visualization`,onSelect:()=>j(C.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:C.label})]})},C.id)})},"default");if(w==="standardPlugin"){const C=l.filter(v=>v.pluginType==="standard");return C.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=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:C.filter(v=>v.componentType==="chart").map((v,k)=>e.jsx(Qs,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"standardPlugin"):null}if(w==="customPlugin"){const C=l.filter(v=>v.pluginType==="custom");return C.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=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:C.map((v,k)=>e.jsx(Qs,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"customPlugin"):null}return null})]})]})})]})})}const Dl=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(He,{className:"h-4 w-4"})},Tl=[{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 kl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:Tl.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:()=>n(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 Rs=({dataType:t})=>{const n=s.getDataType(t);return n==="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(ve,{className:"h-3 w-3"})}):n==="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(De,{className:"h-3 w-3"})}):n==="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"})}):n==="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(Re,{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(ve,{className:"h-3 w-3"})})};function El({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a: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&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==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:()=>{n(a),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 Il({valueAliases:t,onValueAliasesChange:n}){const[a,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),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,x],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.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(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"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 Al({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const p=b[x]||b[t.alias||x]||b[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function Ml({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var T,I;const c=!!l,[i,d]=M.useState(c?"values":"fields"),[u,m]=M.useState(""),[h,x]=M.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=a.filter(w=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(k=>k.field.id===w.id))&&w.label.toLowerCase().includes(u.toLowerCase())}),b=w=>{x({...h,field:w}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const w={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let C;if(c){const v=((r==null?void 0:r.conditions)||[]).map(k=>k.id===l.id?w:k);C={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];C={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,w],groups:[]}}o(C),n(!1)}},j=()=>{if(!c||!l)return;const w=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==l.id);if(w.length>0){const C={...r,conditions:w};o(C)}else o(void 0);n(!1)},f=w=>{x({...h,selectedValues:w})},N=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return M.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,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 ${(I=h.field)==null?void 0:I.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(w=>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:[w.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(w.value)?`${w.value.length} values`:String(w.value)})]},w.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:w=>m(w.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(w=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(w),children:[e.jsx(Rs,{dataType:s.getDataType(w.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:w.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.entityName,".",w.name]})]})]},w.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&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ll,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,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:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ll({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=M.useState(""),{values:c,isLoading:i,isFetching:d}=Al({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const g=n.includes(x);a(g?n.filter(b=>b!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.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:x=>o(x.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:n.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(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(cs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Rl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Fs,Ps,Bs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),g=s.useEditorStore(K=>K.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:I,handleKpiComparisonTypeChange:w,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:y}=Ls(g),[O,E]=M.useState(!1),[P,D]=M.useState(!1),[S,L]=M.useState(null),[F,R]=M.useState(t.dateFormat||"YYYY-MM-DD"),[A,z]=M.useState(t.customFormat||""),[q,V]=M.useState(!!t.customFormat),[J,Z]=M.useState(t.granularity||"day"),[W,H]=M.useState(t.aliasTemplate||""),[G,se]=M.useState(t.valueAliases||{}),[_,U]=M.useState((Fs=t.parameters)==null?void 0:Fs.filters),ee=K=>{K==="custom"?V(!0):(V(!1),R(K),n==="groupBy"&&j(a,K,""))},ne=K=>{z(K),n==="groupBy"&&j(a,"custom",K)},oe=K=>{var ge;Z(K);const ue=(ge=Q(K)[0])==null?void 0:ge.value;ue&&!q&&(R(ue),n==="groupBy"&&j(a,ue,"")),n==="groupBy"&&f(a,K)},B=K=>{H(K),n==="metrics"&&N(a,K)},ae=K=>{se(K),n==="metrics"&&T(a,K)},le=K=>{b(n,a,K)},re=K=>{var de;if(U(K),n==="metrics"){const ue={...t,parameters:{...t.parameters,filters:K}},ge=[...((de=g.config)==null?void 0:de.metricColumns)||[]];ge[a]=ue,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ge})}D(!1)},xe=()=>{I(n,a)},pe={transform:s.CSS.Transform.toString(m),transition:h},me=s.getDataType(t.dataType),fe=me==="date",Y=c==="kpi",Q=K=>{switch(K){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..."}]}},X=Q(J),$=n!=="pivotBy",te=fe&&n==="groupBy",ie=!Y&&fe&&n==="groupBy",ce=Y&&fe&&n==="groupBy",Ee=Y&&n==="metrics"&&((Ps=g.config)==null?void 0:Ps.comparisonType)==="target",Ge=n==="metrics",Ye=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.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}`}),Te=()=>$?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:le,placeholder:"Display label...",type:"text"})]}):null,he=()=>te?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:J,onValueChange:oe,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(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,qt=()=>ie?e.jsxs(e.Fragment,{children:[he(),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:q?"custom":F,onValueChange:ee,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:X.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),q&&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:A,onChange:K=>{K.stopPropagation(),ne(K.target.value)},onClick:K=>K.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,Ht=()=>{var K,de,ue,ge,ke;return ce?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:((K=g.config)==null?void 0:K.comparisonType)||"none",onValueChange:w,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:((de=g.config)==null?void 0:de.showTrendline)||!1,onCheckedChange:C})]})}),((ue=g.config)==null?void 0:ue.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:((ge=g.config)==null?void 0:ge.trendlineWindow)||30,onChange:Qe=>{const Xt=parseInt(Qe.target.value)||30;v(Xt)},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:((ke=g.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:k,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},Wt=()=>{var K,de;return Ee?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(we,{value:((K=g.config)==null?void 0:K.targetValue)!==void 0&&((de=g.config)==null?void 0:de.targetValue)!==null?String(g.config.targetValue):"",onSave:ue=>{!isNaN(Number(ue))&&ue!==null?y(Number(ue)):y(0)},placeholder:"Enter target value...",type:"text"})]}):null},Kt=()=>Ge?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:K=>{p(a,K)},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"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(K=>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:()=>{L(K),D(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.field.label,":"]}),e.jsx(s.TooltipProvider,{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(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.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 (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((de,ue)=>e.jsx("div",{children:String(de)},ue))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var ge;de.stopPropagation();const ue=_.conditions.filter(ke=>ke.id!==K.id);if(ue.length>0){const ke={..._,conditions:ue};re(ke)}else if(U(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Qe=[...((ge=g.config)==null?void 0:ge.metricColumns)||[]];Qe[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Qe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{L(null),D(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(_t,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(El,{aliasTemplate:W,onAliasTemplateChange:B}),e.jsx(Il,{valueAliases:G,onValueAliasesChange:ae})]})]}):null,{columns:Qt=[]}=s.useColumns(),Jt=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:pe,...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 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Rs,{dataType:me}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-xs",Jt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Bs=_==null?void 0:_.conditions)==null?void 0:Bs.length)&&!O&&e.jsx(s.TooltipProvider,{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:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),E(!O)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${O?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const de=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",de),l(de)},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",onClick:K=>{K.stopPropagation(),xe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[Ye(),Te(),c==="kpi"&&he(),qt(),Ht(),Wt(),Kt()]})]}),P&&e.jsx(Ml,{open:P,onOpenChange:K=>{D(K),K||L(null)},availableFields:Qt,existingFilters:_,editingCondition:S,onSave:K=>{var de;if(K)re(K);else if(U(void 0),n==="metrics"){const ue={...t,parameters:{...t.parameters,filters:void 0}},ge=[...((de=g.config)==null?void 0:de.metricColumns)||[]];ge[a]=ue,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ge})}L(null)}})]})}function Ol({concept:t}){const n=()=>{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,{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:n()})]})})}function Ze({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,x=(b,p)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(N=>N.id===b)===-1||d(u.id,b,{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:a}),g&&e.jsx(Ol,{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:n.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:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,p)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Rl,{field:b,zone:t,index:p,sortDirection:f,onSortDirectionChange:N=>x(b.id,N),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Fl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,l]=M.useState(!1),[o,c]=M.useState(!1),i=()=>{const d=Xs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Xs[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 ${a}`})}),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:Fl.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:()=>{n(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:a})]}),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(Rt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const es={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%
340
- 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 Pl(){var i,d,u,m,h,x,g,b,p,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...f}}};n(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(ba,{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:f=>c({enabled:f,...f&&!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:f=>c({calculationType:f}),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(es).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,T,I;const f=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=es[f])==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=es[f])==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:"})," ",(I=es[f])==null?void 0:I.example]})]})})()]}),e.jsx(As,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),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:f=>c({position:f}),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:f=>c({showArrow:f})}),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:f=>c({showColor:f})}),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(js,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),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:f=>c({conditionalLabel:f})}),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:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.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:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.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:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.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:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Bl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((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}};n(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(De,{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(As,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function zl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>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(s.List,{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(Ze,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(Ze,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Ze,{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(Bl,{}),e.jsx(Pl,{}),e.jsx(Ot,{}),e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{})]})})]})]})}function _l({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.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 border-x border-border",children:[e.jsxs("div",{className:"space-y-2 px-6 pt-4",children:[e.jsx(wl,{selectedChart:t,onChartChange:n}),e.jsx(kl,{selectedChart:t,onChartChange:n})]}),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(os,{})}),!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(zl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Vl({initialFilters:t,availableFields:n}={}){const[a,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(w=>w.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const C=v=>{if(v.id===w){const k=i[0]||d,y=s.getDataType(k.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:k,operator:y?"between":"=",value:y?[]:""}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},m=w=>{const C=v=>{if(v.id===w){const k=i[0]||d,y=s.getDataType(k.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},h=(w,C)=>{const v=k=>k.id===w?{...k,conditions:k.conditions.filter(y=>y.id!==C)}:{...k,groups:k.groups.map(v)};r(v(a))},x=(w,C)=>{const v=k=>k.id===w?{...k,groups:k.groups.filter(y=>y.id!==C)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(w,C,v,k)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=O=>O.id===w?{...O,conditions:O.conditions.map(E=>E.id===C?{...E,[v]:k}:E)}:{...O,groups:O.groups.map(y)};r(y(a))},b=(w,C,v)=>{const k=y=>y.id===w?{...y,conditions:y.conditions.map(O=>O.id===C?{...O,...v}:O)}:{...y,groups:y.groups.map(k)};r(k(a))},p=(w,C)=>{const v=k=>k.id===w?{...k,logicalOperator:C}:{...k,groups:k.groups.map(v)};r(v(a))},j=(w,C)=>{const v=k=>k.id===w?{...k,negate:C}:{...k,groups:k.groups.map(v)};r(v(a))},f=(w,C,v)=>{const k=y=>y.id===w?{...y,conditions:s.arrayMove(y.conditions,C,v)}:{...y,groups:y.groups.map(k)};r(k(a))},N=(w,C,v)=>{const k=y=>y.id===w?{...y,groups:s.arrayMove(y.groups,C,v)}:{...y,groups:y.groups.map(k)};r(k(a))},T=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const C=k=>{let y="";typeof k.field=="object"?y=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:y=String(k.field);const O=k.operator;let E=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof E=="string"?E=`'${E}'`:Array.isArray(E)&&(E=`'${E.join(", ")}'`);else if(k.field.dataType==="date"||k.field.dataType==="datetime"||k.field.dataType==="timestamp")if(k.operator==="between"&&Array.isArray(E)&&E.length===2){const P=E[0]?`'${E[0]}'`:"NULL",D=E[1]?`'${E[1]}'`:"NULL";return`${y} BETWEEN ${P} AND ${D}`}else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(E)){const P=E.map(D=>D?`'${D}'`:"NULL").join(", ");return`${y} ${O} (${P})`}else typeof E=="string"||E instanceof Date?E=`'${E}'`:Array.isArray(E)&&E.length>0&&(E=`'${E[0]}'`);else if(["in","not in"].includes(k.operator)){let P=[];Array.isArray(E)?P=E.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof E=="string"?P=E.split(",").map(D=>{const S=D.trim();return k.field.dataType==="string"?`'${S}'`:S}):typeof E=="number"&&(P=[String(E)]),E=`(${P.join(", ")})`}switch(O){case"contains":return typeof E=="string"?`${y} LIKE '%${E.replace(/'/g,"")}'`:`${y} LIKE '%${String(E)}'`;case"startsWith":return typeof E=="string"?`${y} LIKE '${E.replace(/'/g,"")}%'`:`${y} LIKE '${String(E)}%'`;case"endsWith":return typeof E=="string"?`${y} LIKE '%${E.replace(/'/g,"")}'`:`${y} LIKE '%${String(E)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${O} ${E}`}},v=k=>{const y=k.conditions.map(C),O=k.groups.map(S=>v(S)),E=[...y,...O].filter(Boolean);if(E.length===0)return"";const P=E.join(` ${k.logicalOperator} `),D=E.length>1?`(${P})`:P;return k.negate?`NOT ${D}`:D};return v(w)},I=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:I}}function Ul({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Gl=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"})}},Yl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function $l({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return a.forEach(u=>{const m=Yl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);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(Ul,{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:[Gl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),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)===x.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:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var p;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:g}}function ql({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ie.useState(!1),{filterValues:i}=Os(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,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:n.length>0?n.map(m=>{const h=i.find(x=>x.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:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.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",n.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 Hl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Os(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:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),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 Wl({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=M.useMemo(()=>{if(t){if(n==="between"||n==="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(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="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,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Kl=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ql=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Jl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Xl=["=","!=","isNull","isNotNull"],Zl=["between","isNull","isNotNull"],eo={"=":"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 Zs(t){return eo[t]||s.titleCase(t)}function so(t){switch(t){case"string":return Ql;case"number":return Jl;case"boolean":return Xl;case"date":return Zl;default:return Kl}}function Ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=Os(t.field),f={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"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"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx($l,{value:t.field,onValueChange:N=>{const T=N,I=s.getDataType(T.dataType)==="date";d(a,t.id,{field:T,value:"",operator:I?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(a,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?d(a,t.id,{operator:N,value:null}):d(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Zs(t.operator):""})}),e.jsx(s.SelectContent,{children:so(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:Zs(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(ql,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(a,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(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Hl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(a,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(a,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(Wl,{value:t.value,operator:t.operator,onChange:N=>d(a,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(a,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(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function to({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:f,setNodeRef:N,transform:T,transition:I,isDragging:w}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(T),transition:I},v=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id){const P=t.conditions.findIndex(S=>S.id===O.id),D=t.conditions.findIndex(S=>S.id===E.id);P!==-1&&D!==-1&&u(t.id,P,D)}},k=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id&&a){const P=t.groups.findIndex(S=>S.id===O.id),D=t.groups.findIndex(S=>S.id===E.id);P!==-1&&D!==-1&&m(a,P,D)}};return e.jsxs("div",{ref:N,style:C,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${w?"z-50 opacity-50":""}`,children:[n>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,...f,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:y=>r(t.id,y),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:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>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(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((y,O)=>e.jsx(Ut,{condition:y,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},y.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>b(y,n+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:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ao({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:I}=Vl({initialFilters:t,availableFields:n}),w=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,v]=M.useState(!1),k=(E,P,D)=>{const S=L=>L.id===E?{...L,conditions:L.conditions.map(F=>F.id===P?{...F,field:D,dataType:D.dataType}:F)}:{...L,groups:L.groups.map(S)};I(S(o))},y=(E,P=0,D)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:F}=S;if(F&&L.id!==F.id){const R=E.conditions.findIndex(z=>z.id===L.id),A=E.conditions.findIndex(z=>z.id===F.id);R!==-1&&A!==-1&&j(E.id,R,A)}},children:e.jsx(s.SortableContext,{items:E.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:E.conditions.map((S,L)=>e.jsx(Ut,{condition:S,index:L,groupId:E.id,groupLogicalOperator:E.logicalOperator,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},S.id))})}),e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:F}=S;if(F&&L.id!==F.id){const R=E.groups.findIndex(z=>z.id===L.id),A=E.groups.findIndex(z=>z.id===F.id);R!==-1&&A!==-1&&f(E.id,R,A)}},children:e.jsx(s.SortableContext,{items:E.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:E.groups.map(S=>y(S,P+1,E.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(E.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(E.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},E.id):e.jsx(to,{group:E,depth:P,parentGroupId:D,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:y,updateConditionFields:g},E.id),O=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..."})]}):y(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:C,onCheckedChange:E=>v(!!E)}),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"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function no({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(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(ao,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ro({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=M.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=M.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=M.useCallback(b=>{o(b.active.id)},[]),h=M.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const f=p.id,N=j.id,T=u(f),I=u(N)||N;if(I==="sortBy"){if(T==="source"){const w=n.find(v=>v.id===f);if(!w){o(null);return}if(!(a("groupBy").some(v=>v.name===w.name&&v.qualifiedEntityName===w.qualifiedEntityName)||a("metrics").some(v=>v.name===w.name&&v.qualifiedEntityName===w.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"&&I==="sortBy"){const w=[...n].find(k=>k.id===f);if(!w){o(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(w,C)){o(null);return}const v=s.getNewField(w,"sortBy",C);o(null),r("sortBy",[...C,v]);return}if(T==="source"&&I!=="source"&&I!=="sortBy"){const w=[...n].find(y=>y.id===f);if(!w){o(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const y=C[0].qualifiedEntityName;if(!y){o(null);return}if(y!==w.qualifiedEntityName&&w.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(y,w.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(I);if(s.fieldAlreadyExists(w,v)){o(null);return}const k=s.getNewField(w,I,v);o(null),r(I,[...v,k]);return}if(T&&I&&T!=="source"&&I!=="source"&&T!==I){const w=a(T),C=a(I),v=w.find(O=>O.id===f);if(!v){o(null);return}const k=s.getNewField(v,I,C);if(o(null),I==="sortBy"){s.fieldAlreadyExists(v,C)||r(I,[...C,k]);return}const y=w.filter(O=>O.id!==f);r(T,y),r(I,[...C,k]);return}if(T&&I&&T===I&&T!=="source"){const w=a(T),C=w.findIndex(k=>k.id===f),v=w.findIndex(k=>k.id===N);if(C!==v){const k=s.arrayMove(w,C,v);r(T,k)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function lo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>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})]}),x=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,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),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:[n," Card filter",n!==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:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function oo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=M.useState(!1),c=s.useEditorStore(f=>f.isDevMode),i=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.card.dataSource);s.isExplorerCard(i);const{config:u}=M.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),x=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),b=s.useManagementStore(f=>f.selectedVisual),p=(b==null?void 0:b.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",x&&"justify-end",!m&&"justify-end"),children:[m&&t&&!x&&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(Es,{}),a&&!p&&e.jsx(ks,{variant:"default"}),p&&e.jsx(Kn,{}),n&&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 io({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=M.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),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"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const co=[{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 uo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=M.useState(!1),[l,o]=M.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?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:co.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function mo({isOpen:t,onClose:n}){const a=dt(n,{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=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,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:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function ho(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},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 xo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function po({open:t,onOpenChange:n,feedbackData:a}){var p,j,f,N,T,I;const[r,l]=M.useState(""),[o,c]=M.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=ho(),x=()=>{const w={...a,userMessage:r.trim()||void 0};i(w)},g=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(p=a.systemState)==null?void 0:p.errorMessage,sql:(j=a.systemState)==null?void 0:j.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(T=a.systemState)==null?void 0:T.dataSource,filters:(I=a.systemState)==null?void 0:I.dashboardFilters,metadata:a.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:w=>l(w.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(b,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:x,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(ca,{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 Gt=(t=>(t.QUERY_GENERATION="query-generation",t))(Gt||{});function fo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:x}){var _;const g=s.useEditorStore(U=>U.card),b=s.useDashboardStore(U=>U.filterValues),p=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:f,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:I}=s.useDashboardActions(),[w,C]=M.useState(null),v=s.useEditorStore(U=>U.showAIDialog),[k,y]=M.useState(!1),[O,E]=M.useState(!1),[P,D]=M.useState(null),{isConsoleMode:S}=s.useDashboardPreferences(),{config:L}=M.useContext(s.SemaphorContext).tokenProps,F=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(U=>{var ee;return((ee=U.card.customCardPreferences)==null?void 0:ee.url)&&U.card.type==="custom"}),{data:A,errorMessage:z,isLoading:q,isFetching:V,errorSql:J,pagination:Z}=s.useDashboardCardQuery(u),W=(U,ee)=>{const ne={...u,paginationConfig:{page:U+1,pageSize:ee}};f(ne),N(ne)};function H(){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(b||{},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...":x?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const G=U=>{if(!g.config)return;if(!U.length){j(g.id,{...g.config,sortByColumns:[]});return}const ee=g.config,ne=U.map(({id:oe,desc:B})=>{var xe,pe;const ae=(xe=ee.metricColumns)==null?void 0:xe.find(me=>me.label===oe),le=(pe=ee.groupByColumns)==null?void 0:pe.find(me=>me.label===oe),re=ae||le;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:B?"desc":"asc"}:null}).filter(oe=>oe!==null);j(g.id,{...ee,sortByColumns:ne})},se=M.useMemo(()=>{var U,ee;return(ee=(U=g.config)==null?void 0:U.sortByColumns)==null?void 0:ee.map(ne=>({id:ne.label,desc:ne.direction==="desc"}))},[(_=g.config)==null?void 0:_.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(oo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&H(),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(Tt,{variant:"outline"}),e.jsx(io,{activeView:t,onViewChange:n}),i&&e.jsx(lo,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(uo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(kt,{})})]}),!k&&R&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>y(!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(Et,{})}),t==="table"&&(A==null?void 0:A.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:(A==null?void 0:A.records)||[],paginationMetadata:Z,onPaginationChange:W,isLoading:q||V,onSortChange:G,sortState:se})}),t==="info"&&F&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[S&&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:U=>{const ee=s.sanitizeCardId(U);if(!ee){C("Card ID cannot be empty");return}const ne=I(g.id,ee);if(ne.success){T(ee);const oe={...g,id:ee};f(oe),N(oe),C(null),s.ue.success("Card ID updated successfully")}else C(ne.error||"Failed to update Card ID"),s.ue.error(ne.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"})]}),w&&e.jsx("p",{className:"text-xs text-destructive",children:w})]}),z||J?e.jsx(bt,{error:z,errorSql:J,onSendFeedback:()=>{const U=xo(Gt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:z,errorSql:J,generatedSql:A==null?void 0:A.sql});D(U),E(!0)}}):e.jsxs(e.Fragment,{children:[(A==null?void 0:A.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(vt,{sql:A==null?void 0:A.sql,error:z,errorSql:J})]})]})})]}),e.jsx(mo,{isOpen:k,onClose:()=>y(!1)}),P&&e.jsx(po,{open:O,onOpenChange:E,feedbackData:P})]})]})}function go({activeField:t}){const[n,a]=M.useState(!0);return M.useEffect(()=>{t&&a(!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 ${n?"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(Rs,{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 jo=()=>{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 n=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},a=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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function bo(){var Z,W;const[t,n]=M.useState("chart"),[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),u=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);M.useEffect(()=>jo(),[]);const x=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=H=>{m(H)},f=s.useEditorStore(H=>H.frame),N=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:T,removeCard:I,updateCard:w,setActiveCard:C,updateFilters:v}=s.useEditorActions(),{columns:k=[],isLoading:y,error:O}=s.useColumns(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),P=N,{getFieldsForContainer:D,setFieldsForContainer:S}=Ls(P),{activeField:L,handleDragStart:F,handleDragEnd:R}=ro({activeCardId:f.activeCardId,sourceFields:k,getFieldsForContainer:D,setFieldsForContainer:S}),A=(H,G)=>{G&&v(H,G)},z=H=>{var G;w(H,{config:{...(G=f.cards.find(se=>se.id===H))==null?void 0:G.config,filters:void 0}})},q=k,V=H=>{if(!H)return 0;let G=H.conditions.length;return H.groups.forEach(se=>{G+=V(se)}),G},J=V(((Z=P==null?void 0:P.config)==null?void 0:Z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:F,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Nl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(_l,{selectedChart:h,onChartChange:j,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy")}),e.jsx(fo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:x,onClear:g,onAdvancedToggle:b,onFiltersClick:p,filterCount:J,activeCard:P,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:y,columnsError:O,getFieldsForContainer:D,cards:f.cards,activeCardId:f.activeCardId,addCard:T,setActiveCard:C})]}),!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"})})})]}),P&&e.jsx(no,{cardId:P.id,filters:((W=P.config)==null?void 0:W.filters)||null,onFiltersChange:A,onClearFilters:z,availableFields:q,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(go,{activeField:L||null})})]})}function vo({authToken:t,onSave:n,onClose:a}){const r=M.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:x,handleDragCancel:g,sensors:b}=Bn();M.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.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(jt,{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(il,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function f(){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(bo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:x,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):f()})}function yo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(vo,{onSave:l,onClose:o})})}function No({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{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(De,{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(Re,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ia,{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 Co(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&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(No,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function So({dataType:t}){const n=s.getDataType(t);return n==="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(ve,{className:"h-3 w-3"})}):n==="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(De,{className:"h-3 w-3"})}):n==="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"})}):n==="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(Re,{className:"h-3 w-3"})}):n==="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(ze,{className:"h-3 w-3"})}):n==="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(qe,{className:"h-3 w-3"})}):n==="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(Ke,{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(ve,{className:"h-3 w-3"})})}function wo(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Is(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const N=s.getDataType(f.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(N,"dashboard",f)};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:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),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:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const N=l==null?void 0:l.some(T=>{var I;return T.title===f.name||((I=T.column)==null?void 0:I.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),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(So,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Do(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.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:a?e.jsx(wo,{}):e.jsx(jt,{type:"filter",ColumnsComponent:()=>e.jsx(Co,{})})})]})}function To(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.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)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.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 ko(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(To,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Do,{})})]})}function Eo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),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),n(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 Yt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function Io({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var C,v,k;const{selectVisual:x}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),p=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[j,f]=M.useState(!1),[N,T]=M.useState(!1);M.useEffect(()=>{a?(f(!0),T(!0)):N&&(f(!1),T(!1))},[a,N]);const I=()=>e.jsx(rs,{className:"h-4 w-4"}),w=()=>{x(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:w,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>i==null?void 0:i(t.id,{title:y}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>i==null?void 0:i(t.id,{description:y}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Ra,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function Ao(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[x,g]=M.useState(!1),[b,p]=M.useState(null),[j,f]=M.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:I,handleAddLibraryVisual:w}=Ts(),{resources:C,isLoading:v,isError:k,createResource:y,updateResource:O,deleteResource:E,duplicateResource:P,isCreating:D,isDeleting:S}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const L=C.filter(U=>{var ee,ne;return((ee=U==null?void 0:U.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((ne=U==null?void 0:U.description)==null?void 0:ne.toLowerCase().includes(t.toLowerCase()))}),F=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&y({title:l,description:c,isPrivate:!1})},A=U=>{p(U),g(!0)},z=()=>{b&&E(b.id)},{startUpdating:q,stopUpdating:V,isUpdating:J}=s.useResourceUpdateState(),Z=(U,ee)=>{const ne=ee.title!==void 0?"title":"description";q(U,ne),O({resourceId:U,data:ee},{onSuccess:()=>{V(U,ne)},onError:()=>{V(U,ne)}})},W=U=>{f(U),P(U,{onSettled:()=>f(null)})},H=U=>{I(U)},G=U=>{w(U)},se=U=>{const ee=C.find(ne=>ne.id===U);ee&&O({resourceId:U,data:{isPrivate:!ee.isPrivate}})},_=U=>{h(U),u(!0)};return v?e.jsx(Yt,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:U=>o(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:U=>i(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||D,children:D?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:D,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:D,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),D?"Creating...":"Create New Visual"]})}),C&&C.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>n(U.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):L.map(U=>e.jsx(Io,{visual:U,onAddVisual:G,onEditVisual:H,onUpdateVisual:Z,onDeleteClick:A,onDuplicateVisual:W,onTogglePrivacy:se,onShareVisual:_,isDeleting:S,isDuplicating:j===U.id,isTitleUpdating:J(U.id,"title"),isDescriptionUpdating:J(U.id,"description"),formatDate:F},U.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:U=>{!U&&S||(g(U),U||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:S?"Deleting...":"Delete"})]})]})})]})}function Mo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var C,v,k;const{selectDashboard:x}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,j]=M.useState(!1),[f,N]=M.useState(!1),T=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);M.useEffect(()=>{a?(j(!0),N(!0)):f&&(j(!1),N(!1))},[a,f]);const I=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),w=()=>{x(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:w,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>c==null?void 0:c(t.id,{title:y}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:y=>y.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function Lo({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Ro(t){const[n,a]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,x]=M.useState(null),[g,b]=M.useState(!1),[p,j]=M.useState(null),[f,N]=M.useState(null),T=s.useManagementStore(B=>B.lastSelectedDashboard),I=s.useManagementStore(B=>B.selectedDashboard),w=s.useManagementStore(B=>B.actions.selectDashboard),C=s.useManagementStore(B=>B.actions.clearSelectedDashboard),{tokenProps:v,id:k}=s.useSemaphorContext(),{permissions:y}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:E,isError:P,createResource:D,updateResource:S,deleteResource:L,duplicateResource:F,isCreating:R,isDeleting:A}=s.useDashboardManagement(()=>{b(!1);const B=p==null?void 0:p.id;j(null),(I==null?void 0:I.id)===B&&(!(v!=null&&v.dashboard_id)&&!k?C():T&&T.id!==B&&w(T))},()=>{l(!1),c(""),d("")}),{currentUser:z}=s.useCurrentUserInfo(),q=O.filter(B=>{var ae,le;return((ae=B==null?void 0:B.title)==null?void 0:ae.toLowerCase().includes(n.toLowerCase()))||((le=B==null?void 0:B.description)==null?void 0:le.toLowerCase().includes(n.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),J=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},Z=B=>{var ae;(ae=t.onLoadDashboard)==null||ae.call(t,B)},W=B=>{j(B),b(!0)},H=()=>{p&&L(p.id)},G=B=>{N(B),F(B,{onSettled:()=>N(null)})},{startUpdating:se,stopUpdating:_,isUpdating:U}=s.useResourceUpdateState(),ee=(B,ae)=>{const le=ae.title!==void 0?"title":"description";se(B,le),S({resourceId:B,data:ae},{onSuccess:()=>{_(B,le)},onError:()=>{_(B,le)}})},ne=B=>{const ae=O.find(le=>le.id===B);ae&&S({resourceId:B,data:{isPrivate:!ae.isPrivate}})},oe=B=>{x(B),z==null||z.type,m(!0)};return E?e.jsx(Yt,{}):P?e.jsx(Lo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[y.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:B=>c(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:B=>d(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:J,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:R,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),R?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:q.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":y.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),y.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):q.map(B=>e.jsx(Mo,{dashboard:B,isDeleting:A,isDuplicating:f===B.id,isTitleUpdating:U(B.id,"title"),isDescriptionUpdating:U(B.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ee,onDeleteClick:W,onDuplicateDashboard:G,onTogglePrivacy:ne,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},B.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),x(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:B=>{!B&&A||(b(B),B||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function $t({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(T=>T.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(T=>T.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,x]=s.useLocalStorageState("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",p=dt(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=T=>{},N=T=>{console.log("Editing dashboard:",T)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:p,className:j,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?x:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Ro,{onLoadDashboard:f,onEditDashboard:N,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(Ao,{})})]})})]})})}function Oo({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen),l=s.useDashboardStore(h=>h.isVisualEditing),o=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=30,i=18,d=35,u=r&&!l;if(typeof window>"u")return null;const{preferences:m}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:m,children:[e.jsx(Eo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Mn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[u&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{className:"flex h-full min-w-[18rem] max-w-[26rem] overflow-hidden",defaultSize:c,minSize:i,maxSize:d,children:e.jsx($t,{isOpen:r,onClose:()=>o(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:!0,className:"w-2"})]}),e.jsx(s.ResizablePanel,{className:"flex min-w-0 flex-1",defaultSize:u?100-c:100,minSize:u?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(yo,{}),e.jsx(ko,{})]})})]},u?"with-management":"without-management")]})]})})]})})}exports.DashboardPlus=Oo;exports.ResourceManagementPanel=$t;exports.ScheduleDashboard=lt;exports.SelectComponent=Pe;exports.ShareDialog=ls;exports.cleanCard=rt;exports.getDashbaordStateWithoutData=ss;
340
+ 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 Pl(){var i,d,u,m,h,x,g,b,p,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...f}}};n(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(ba,{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:f=>c({enabled:f,...f&&!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:f=>c({calculationType:f}),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(es).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,T,I;const f=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=es[f])==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=es[f])==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:"})," ",(I=es[f])==null?void 0:I.example]})]})})()]}),e.jsx(As,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),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:f=>c({position:f}),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:f=>c({showArrow:f})}),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:f=>c({showColor:f})}),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(js,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),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:f=>c({conditionalLabel:f})}),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:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.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:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.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:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.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:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Bl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((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}};n(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(De,{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(As,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function zl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>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(s.List,{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(Ze,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(Ze,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ze,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Ze,{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(Bl,{}),e.jsx(Pl,{}),e.jsx(Ot,{}),e.jsx(Ft,{}),e.jsx(Pt,{}),e.jsx(Bt,{})]})})]})]})}function _l({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.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 border-x border-border",children:[e.jsxs("div",{className:"space-y-2 px-6 pt-4",children:[e.jsx(wl,{selectedChart:t,onChartChange:n}),e.jsx(kl,{selectedChart:t,onChartChange:n})]}),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(os,{})}),!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(zl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Vl({initialFilters:t,availableFields:n}={}){const[a,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(w=>w.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const C=v=>{if(v.id===w){const k=i[0]||d,y=s.getDataType(k.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:k,operator:y?"between":"=",value:y?[]:""}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},m=w=>{const C=v=>{if(v.id===w){const k=i[0]||d,y=s.getDataType(k.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},h=(w,C)=>{const v=k=>k.id===w?{...k,conditions:k.conditions.filter(y=>y.id!==C)}:{...k,groups:k.groups.map(v)};r(v(a))},x=(w,C)=>{const v=k=>k.id===w?{...k,groups:k.groups.filter(y=>y.id!==C)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(w,C,v,k)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=O=>O.id===w?{...O,conditions:O.conditions.map(E=>E.id===C?{...E,[v]:k}:E)}:{...O,groups:O.groups.map(y)};r(y(a))},b=(w,C,v)=>{const k=y=>y.id===w?{...y,conditions:y.conditions.map(O=>O.id===C?{...O,...v}:O)}:{...y,groups:y.groups.map(k)};r(k(a))},p=(w,C)=>{const v=k=>k.id===w?{...k,logicalOperator:C}:{...k,groups:k.groups.map(v)};r(v(a))},j=(w,C)=>{const v=k=>k.id===w?{...k,negate:C}:{...k,groups:k.groups.map(v)};r(v(a))},f=(w,C,v)=>{const k=y=>y.id===w?{...y,conditions:s.arrayMove(y.conditions,C,v)}:{...y,groups:y.groups.map(k)};r(k(a))},N=(w,C,v)=>{const k=y=>y.id===w?{...y,groups:s.arrayMove(y.groups,C,v)}:{...y,groups:y.groups.map(k)};r(k(a))},T=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const C=k=>{let y="";typeof k.field=="object"?y=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:y=String(k.field);const O=k.operator;let E=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof E=="string"?E=`'${E}'`:Array.isArray(E)&&(E=`'${E.join(", ")}'`);else if(k.field.dataType==="date"||k.field.dataType==="datetime"||k.field.dataType==="timestamp")if(k.operator==="between"&&Array.isArray(E)&&E.length===2){const P=E[0]?`'${E[0]}'`:"NULL",D=E[1]?`'${E[1]}'`:"NULL";return`${y} BETWEEN ${P} AND ${D}`}else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(E)){const P=E.map(D=>D?`'${D}'`:"NULL").join(", ");return`${y} ${O} (${P})`}else typeof E=="string"||E instanceof Date?E=`'${E}'`:Array.isArray(E)&&E.length>0&&(E=`'${E[0]}'`);else if(["in","not in"].includes(k.operator)){let P=[];Array.isArray(E)?P=E.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof E=="string"?P=E.split(",").map(D=>{const S=D.trim();return k.field.dataType==="string"?`'${S}'`:S}):typeof E=="number"&&(P=[String(E)]),E=`(${P.join(", ")})`}switch(O){case"contains":return typeof E=="string"?`${y} LIKE '%${E.replace(/'/g,"")}'`:`${y} LIKE '%${String(E)}'`;case"startsWith":return typeof E=="string"?`${y} LIKE '${E.replace(/'/g,"")}%'`:`${y} LIKE '${String(E)}%'`;case"endsWith":return typeof E=="string"?`${y} LIKE '%${E.replace(/'/g,"")}'`:`${y} LIKE '%${String(E)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${O} ${E}`}},v=k=>{const y=k.conditions.map(C),O=k.groups.map(S=>v(S)),E=[...y,...O].filter(Boolean);if(E.length===0)return"";const P=E.join(` ${k.logicalOperator} `),D=E.length>1?`(${P})`:P;return k.negate?`NOT ${D}`:D};return v(w)},I=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:I}}function Ul({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Gl=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"})}},Yl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function $l({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return a.forEach(u=>{const m=Yl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);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(Ul,{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:[Gl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),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)===x.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:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var p;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:g}}function ql({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ie.useState(!1),{filterValues:i}=Os(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,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:n.length>0?n.map(m=>{const h=i.find(x=>x.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:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.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",n.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 Hl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Os(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:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),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 Wl({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=M.useMemo(()=>{if(t){if(n==="between"||n==="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(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="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,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Kl=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ql=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Jl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Xl=["=","!=","isNull","isNotNull"],Zl=["between","isNull","isNotNull"],eo={"=":"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 Zs(t){return eo[t]||s.titleCase(t)}function so(t){switch(t){case"string":return Ql;case"number":return Jl;case"boolean":return Xl;case"date":return Zl;default:return Kl}}function Ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=Os(t.field),f={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"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"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx($l,{value:t.field,onValueChange:N=>{const T=N,I=s.getDataType(T.dataType)==="date";d(a,t.id,{field:T,value:"",operator:I?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?d(a,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?d(a,t.id,{operator:N,value:null}):d(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Zs(t.operator):""})}),e.jsx(s.SelectContent,{children:so(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:Zs(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(ql,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>d(a,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(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Hl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>d(a,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(a,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(Wl,{value:t.value,operator:t.operator,onChange:N=>d(a,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(a,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(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function to({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:f,setNodeRef:N,transform:T,transition:I,isDragging:w}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(T),transition:I},v=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id){const P=t.conditions.findIndex(S=>S.id===O.id),D=t.conditions.findIndex(S=>S.id===E.id);P!==-1&&D!==-1&&u(t.id,P,D)}},k=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id&&a){const P=t.groups.findIndex(S=>S.id===O.id),D=t.groups.findIndex(S=>S.id===E.id);P!==-1&&D!==-1&&m(a,P,D)}};return e.jsxs("div",{ref:N,style:C,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${w?"z-50 opacity-50":""}`,children:[n>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,...f,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:y=>r(t.id,y),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:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>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(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((y,O)=>e.jsx(Ut,{condition:y,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},y.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>b(y,n+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:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ao({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:I}=Vl({initialFilters:t,availableFields:n}),w=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,v]=M.useState(!1),k=(E,P,D)=>{const S=L=>L.id===E?{...L,conditions:L.conditions.map(F=>F.id===P?{...F,field:D,dataType:D.dataType}:F)}:{...L,groups:L.groups.map(S)};I(S(o))},y=(E,P=0,D)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:F}=S;if(F&&L.id!==F.id){const R=E.conditions.findIndex(z=>z.id===L.id),A=E.conditions.findIndex(z=>z.id===F.id);R!==-1&&A!==-1&&j(E.id,R,A)}},children:e.jsx(s.SortableContext,{items:E.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:E.conditions.map((S,L)=>e.jsx(Ut,{condition:S,index:L,groupId:E.id,groupLogicalOperator:E.logicalOperator,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},S.id))})}),e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:S=>{const{active:L,over:F}=S;if(F&&L.id!==F.id){const R=E.groups.findIndex(z=>z.id===L.id),A=E.groups.findIndex(z=>z.id===F.id);R!==-1&&A!==-1&&f(E.id,R,A)}},children:e.jsx(s.SortableContext,{items:E.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:E.groups.map(S=>y(S,P+1,E.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(E.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(E.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},E.id):e.jsx(to,{group:E,depth:P,parentGroupId:D,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:y,updateConditionFields:g},E.id),O=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..."})]}):y(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:C,onCheckedChange:E=>v(!!E)}),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"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function no({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(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(ao,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ro({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=M.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=M.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=M.useCallback(b=>{o(b.active.id)},[]),h=M.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const f=p.id,N=j.id,T=u(f),I=u(N)||N;if(I==="sortBy"){if(T==="source"){const w=n.find(v=>v.id===f);if(!w){o(null);return}if(!(a("groupBy").some(v=>v.name===w.name&&v.qualifiedEntityName===w.qualifiedEntityName)||a("metrics").some(v=>v.name===w.name&&v.qualifiedEntityName===w.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"&&I==="sortBy"){const w=[...n].find(k=>k.id===f);if(!w){o(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(w,C)){o(null);return}const v=s.getNewField(w,"sortBy",C);o(null),r("sortBy",[...C,v]);return}if(T==="source"&&I!=="source"&&I!=="sortBy"){const w=[...n].find(y=>y.id===f);if(!w){o(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const y=C[0].qualifiedEntityName;if(!y){o(null);return}if(y!==w.qualifiedEntityName&&w.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(y,w.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(I);if(s.fieldAlreadyExists(w,v)){o(null);return}const k=s.getNewField(w,I,v);o(null),r(I,[...v,k]);return}if(T&&I&&T!=="source"&&I!=="source"&&T!==I){const w=a(T),C=a(I),v=w.find(O=>O.id===f);if(!v){o(null);return}const k=s.getNewField(v,I,C);if(o(null),I==="sortBy"){s.fieldAlreadyExists(v,C)||r(I,[...C,k]);return}const y=w.filter(O=>O.id!==f);r(T,y),r(I,[...C,k]);return}if(T&&I&&T===I&&T!=="source"){const w=a(T),C=w.findIndex(k=>k.id===f),v=w.findIndex(k=>k.id===N);if(C!==v){const k=s.arrayMove(w,C,v);r(T,k)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function lo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>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})]}),x=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,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),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:[n," Card filter",n!==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:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function oo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=M.useState(!1),c=s.useEditorStore(f=>f.isDevMode),i=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.card.dataSource);s.isExplorerCard(i);const{config:u}=M.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),x=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),b=s.useManagementStore(f=>f.selectedVisual),p=(b==null?void 0:b.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",x&&"justify-end",!m&&"justify-end"),children:[m&&t&&!x&&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(Es,{}),a&&!p&&e.jsx(ks,{variant:"default"}),p&&e.jsx(Kn,{}),n&&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 io({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=M.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),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"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const co=[{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 uo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=M.useState(!1),[l,o]=M.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?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:co.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function mo({isOpen:t,onClose:n}){const a=dt(n,{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=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,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:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function ho(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},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 xo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function po({open:t,onOpenChange:n,feedbackData:a}){var p,j,f,N,T,I;const[r,l]=M.useState(""),[o,c]=M.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=ho(),x=()=>{const w={...a,userMessage:r.trim()||void 0};i(w)},g=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(p=a.systemState)==null?void 0:p.errorMessage,sql:(j=a.systemState)==null?void 0:j.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(T=a.systemState)==null?void 0:T.dataSource,filters:(I=a.systemState)==null?void 0:I.dashboardFilters,metadata:a.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:w=>l(w.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(b,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:x,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(ca,{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 Gt=(t=>(t.QUERY_GENERATION="query-generation",t))(Gt||{});function fo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:x}){var _;const g=s.useEditorStore(U=>U.card),b=s.useDashboardStore(U=>U.filterValues),p=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:f,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:I}=s.useDashboardActions(),[w,C]=M.useState(null),v=s.useEditorStore(U=>U.showAIDialog),[k,y]=M.useState(!1),[O,E]=M.useState(!1),[P,D]=M.useState(null),{isConsoleMode:S}=s.useDashboardPreferences(),{config:L}=M.useContext(s.SemaphorContext).tokenProps,F=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(U=>{var ee;return((ee=U.card.customCardPreferences)==null?void 0:ee.url)&&U.card.type==="custom"}),{data:A,errorMessage:z,isLoading:q,isFetching:V,errorSql:J,pagination:Z}=s.useDashboardCardQuery(u),W=(U,ee)=>{const ne={...u,paginationConfig:{page:U+1,pageSize:ee}};f(ne),N(ne)};function H(){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(b||{},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...":x?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const G=U=>{if(!g.config)return;if(!U.length){j(g.id,{...g.config,sortByColumns:[]});return}const ee=g.config,ne=U.map(({id:oe,desc:B})=>{var xe,pe;const ae=(xe=ee.metricColumns)==null?void 0:xe.find(me=>me.label===oe),le=(pe=ee.groupByColumns)==null?void 0:pe.find(me=>me.label===oe),re=ae||le;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:B?"desc":"asc"}:null}).filter(oe=>oe!==null);j(g.id,{...ee,sortByColumns:ne})},se=M.useMemo(()=>{var U,ee;return(ee=(U=g.config)==null?void 0:U.sortByColumns)==null?void 0:ee.map(ne=>({id:ne.label,desc:ne.direction==="desc"}))},[(_=g.config)==null?void 0:_.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(oo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),a&&H(),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(Tt,{variant:"outline"}),e.jsx(io,{activeView:t,onViewChange:n}),i&&e.jsx(lo,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(uo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(kt,{})})]}),!k&&R&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>y(!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(Et,{})}),t==="table"&&(A==null?void 0:A.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:(A==null?void 0:A.records)||[],paginationMetadata:Z,onPaginationChange:W,isLoading:q||V,onSortChange:G,sortState:se})}),t==="info"&&F&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[S&&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:U=>{const ee=s.sanitizeCardId(U);if(!ee){C("Card ID cannot be empty");return}const ne=I(g.id,ee);if(ne.success){T(ee);const oe={...g,id:ee};f(oe),N(oe),C(null),s.ue.success("Card ID updated successfully")}else C(ne.error||"Failed to update Card ID"),s.ue.error(ne.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"})]}),w&&e.jsx("p",{className:"text-xs text-destructive",children:w})]}),z||J?e.jsx(bt,{error:z,errorSql:J,onSendFeedback:()=>{const U=xo(Gt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:z,errorSql:J,generatedSql:A==null?void 0:A.sql});D(U),E(!0)}}):e.jsxs(e.Fragment,{children:[(A==null?void 0:A.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(vt,{sql:A==null?void 0:A.sql,error:z,errorSql:J})]})]})})]}),e.jsx(mo,{isOpen:k,onClose:()=>y(!1)}),P&&e.jsx(po,{open:O,onOpenChange:E,feedbackData:P})]})]})}function go({activeField:t}){const[n,a]=M.useState(!0);return M.useEffect(()=>{t&&a(!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 ${n?"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(Rs,{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 jo=()=>{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 n=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},a=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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function bo(){var Z,W;const[t,n]=M.useState("chart"),[a,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),u=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);M.useEffect(()=>jo(),[]);const x=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=H=>{m(H)},f=s.useEditorStore(H=>H.frame),N=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:T,removeCard:I,updateCard:w,setActiveCard:C,updateFilters:v}=s.useEditorActions(),{columns:k=[],isLoading:y,error:O}=s.useColumns(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),P=N,{getFieldsForContainer:D,setFieldsForContainer:S}=Ls(P),{activeField:L,handleDragStart:F,handleDragEnd:R}=ro({activeCardId:f.activeCardId,sourceFields:k,getFieldsForContainer:D,setFieldsForContainer:S}),A=(H,G)=>{G&&v(H,G)},z=H=>{var G;w(H,{config:{...(G=f.cards.find(se=>se.id===H))==null?void 0:G.config,filters:void 0}})},q=k,V=H=>{if(!H)return 0;let G=H.conditions.length;return H.groups.forEach(se=>{G+=V(se)}),G},J=V(((Z=P==null?void 0:P.config)==null?void 0:Z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:F,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Nl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(_l,{selectedChart:h,onChartChange:j,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy")}),e.jsx(fo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:x,onClear:g,onAdvancedToggle:b,onFiltersClick:p,filterCount:J,activeCard:P,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:y,columnsError:O,getFieldsForContainer:D,cards:f.cards,activeCardId:f.activeCardId,addCard:T,setActiveCard:C})]}),!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"})})})]}),P&&e.jsx(no,{cardId:P.id,filters:((W=P.config)==null?void 0:W.filters)||null,onFiltersChange:A,onClearFilters:z,availableFields:q,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(go,{activeField:L||null})})]})}function vo({authToken:t,onSave:n,onClose:a}){const r=M.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:x,handleDragCancel:g,sensors:b}=Bn();M.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.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(jt,{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(il,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function f(){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(bo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:x,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):f()})}function yo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(vo,{onSave:l,onClose:o})})}function No({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{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(De,{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(Re,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ia,{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 Co(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&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(No,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function So({dataType:t}){const n=s.getDataType(t);return n==="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(ve,{className:"h-3 w-3"})}):n==="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(De,{className:"h-3 w-3"})}):n==="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"})}):n==="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(Re,{className:"h-3 w-3"})}):n==="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(ze,{className:"h-3 w-3"})}):n==="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(qe,{className:"h-3 w-3"})}):n==="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(Ke,{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(ve,{className:"h-3 w-3"})})}function wo(){const[t,n]=M.useState(""),[a,r]=M.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Is(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const N=s.getDataType(f.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(N,"dashboard",f)};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:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),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:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const N=l==null?void 0:l.some(T=>{var I;return T.title===f.name||((I=T.column)==null?void 0:I.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),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(So,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Do(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.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:a?e.jsx(wo,{}):e.jsx(jt,{type:"filter",ColumnsComponent:()=>e.jsx(Co,{})})})]})}function To(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.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)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.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 ko(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(To,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Do,{})})]})}function Eo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),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),n(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 Yt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function Io({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var C,v,k;const{selectVisual:x}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),p=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[j,f]=M.useState(!1),[N,T]=M.useState(!1);M.useEffect(()=>{a?(f(!0),T(!0)):N&&(f(!1),T(!1))},[a,N]);const I=()=>e.jsx(rs,{className:"h-4 w-4"}),w=()=>{x(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:w,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>i==null?void 0:i(t.id,{title:y}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>i==null?void 0:i(t.id,{description:y}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Ra,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function Ao(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[x,g]=M.useState(!1),[b,p]=M.useState(null),[j,f]=M.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:I,handleAddLibraryVisual:w}=Ts(),{resources:C,isLoading:v,isError:k,createResource:y,updateResource:O,deleteResource:E,duplicateResource:P,isCreating:D,isDeleting:S}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const L=C.filter(U=>{var ee,ne;return((ee=U==null?void 0:U.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((ne=U==null?void 0:U.description)==null?void 0:ne.toLowerCase().includes(t.toLowerCase()))}),F=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&y({title:l,description:c,isPrivate:!1})},A=U=>{p(U),g(!0)},z=()=>{b&&E(b.id)},{startUpdating:q,stopUpdating:V,isUpdating:J}=s.useResourceUpdateState(),Z=(U,ee)=>{const ne=ee.title!==void 0?"title":"description";q(U,ne),O({resourceId:U,data:ee},{onSuccess:()=>{V(U,ne)},onError:()=>{V(U,ne)}})},W=U=>{f(U),P(U,{onSettled:()=>f(null)})},H=U=>{I(U)},G=U=>{w(U)},se=U=>{const ee=C.find(ne=>ne.id===U);ee&&O({resourceId:U,data:{isPrivate:!ee.isPrivate}})},_=U=>{h(U),u(!0)};return v?e.jsx(Yt,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:U=>o(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:U=>i(U.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||D,children:D?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:D,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:D,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),D?"Creating...":"Create New Visual"]})}),C&&C.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>n(U.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):L.map(U=>e.jsx(Io,{visual:U,onAddVisual:G,onEditVisual:H,onUpdateVisual:Z,onDeleteClick:A,onDuplicateVisual:W,onTogglePrivacy:se,onShareVisual:_,isDeleting:S,isDuplicating:j===U.id,isTitleUpdating:J(U.id,"title"),isDescriptionUpdating:J(U.id,"description"),formatDate:F},U.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:U=>{!U&&S||(g(U),U||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:S?"Deleting...":"Delete"})]})]})})]})}function Mo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var C,v,k;const{selectDashboard:x}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,j]=M.useState(!1),[f,N]=M.useState(!1),T=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);M.useEffect(()=>{a?(j(!0),N(!0)):f&&(j(!1),N(!1))},[a,f]);const I=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),w=()=>{x(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:w,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>c==null?void 0:c(t.id,{title:y}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:y=>y.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function Lo({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Ro(t){const[n,a]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,x]=M.useState(null),[g,b]=M.useState(!1),[p,j]=M.useState(null),[f,N]=M.useState(null),T=s.useManagementStore(B=>B.lastSelectedDashboard),I=s.useManagementStore(B=>B.selectedDashboard),w=s.useManagementStore(B=>B.actions.selectDashboard),C=s.useManagementStore(B=>B.actions.clearSelectedDashboard),{tokenProps:v,id:k}=s.useSemaphorContext(),{permissions:y}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:E,isError:P,createResource:D,updateResource:S,deleteResource:L,duplicateResource:F,isCreating:R,isDeleting:A}=s.useDashboardManagement(()=>{b(!1);const B=p==null?void 0:p.id;j(null),(I==null?void 0:I.id)===B&&(!(v!=null&&v.dashboard_id)&&!k?C():T&&T.id!==B&&w(T))},()=>{l(!1),c(""),d("")}),{currentUser:z}=s.useCurrentUserInfo(),q=O.filter(B=>{var ae,le;return((ae=B==null?void 0:B.title)==null?void 0:ae.toLowerCase().includes(n.toLowerCase()))||((le=B==null?void 0:B.description)==null?void 0:le.toLowerCase().includes(n.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),J=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},Z=B=>{var ae;(ae=t.onLoadDashboard)==null||ae.call(t,B)},W=B=>{j(B),b(!0)},H=()=>{p&&L(p.id)},G=B=>{N(B),F(B,{onSettled:()=>N(null)})},{startUpdating:se,stopUpdating:_,isUpdating:U}=s.useResourceUpdateState(),ee=(B,ae)=>{const le=ae.title!==void 0?"title":"description";se(B,le),S({resourceId:B,data:ae},{onSuccess:()=>{_(B,le)},onError:()=>{_(B,le)}})},ne=B=>{const ae=O.find(le=>le.id===B);ae&&S({resourceId:B,data:{isPrivate:!ae.isPrivate}})},oe=B=>{x(B),z==null||z.type,m(!0)};return E?e.jsx(Yt,{}):P?e.jsx(Lo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[y.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:B=>c(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:B=>d(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:J,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:R,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),R?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:q.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":y.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),y.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):q.map(B=>e.jsx(Mo,{dashboard:B,isDeleting:A,isDuplicating:f===B.id,isTitleUpdating:U(B.id,"title"),isDescriptionUpdating:U(B.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ee,onDeleteClick:W,onDuplicateDashboard:G,onTogglePrivacy:ne,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},B.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),x(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:B=>{!B&&A||(b(B),B||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function $t({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(T=>T.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(T=>T.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,x]=s.useLocalStorageState("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",p=dt(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=T=>{},N=T=>{console.log("Editing dashboard:",T)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:p,className:j,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?x:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Ro,{onLoadDashboard:f,onEditDashboard:N,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(Ao,{})})]})})]})})}function Oo({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen),l=s.useDashboardStore(h=>h.isVisualEditing),o=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,i=20,d=30,u=r&&!l;if(typeof window>"u")return null;const{preferences:m}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:m,children:[e.jsx(Eo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Mn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":r}),defaultSize:r?c:0,minSize:r?i:0,maxSize:r?d:0,children:e.jsx($t,{isOpen:r,onClose:()=>o(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:r,className:s.cn("w-1",{"w-0":!r})}),e.jsx(s.ResizablePanel,{className:"flex min-w-0 flex-1",defaultSize:u?100-c:100,minSize:u?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(yo,{}),e.jsx(ko,{})]})})]},u?"with-management":"without-management")]})]})})]})})}exports.DashboardPlus=Oo;exports.ResourceManagementPanel=$t;exports.ScheduleDashboard=lt;exports.SelectComponent=Pe;exports.ShareDialog=ls;exports.cleanCard=rt;exports.getDashbaordStateWithoutData=ss;